#include<stdio.h>
#include<conio.h>
int add(int n);
void main()
{
int n, ans;
clrscr();
printf("Enter Number:");
scanf("%d", &n);
ans = add(n);
printf("%d", ans);
getch();
}
int add(int n)
{
if (n==0)
{
return 0;
} else {
return n + add(n-1);
}
}
I have some doubts related recursion programs which have this type of return statements. Can anyone explain me it in a proper way.
I am not able to understand that thing if I am writing return 0 when n==0 then why it returns value from else.Why answer is not 0.I am confused in return statement.
Plz help me.
Thank You In Advance.
Lets take a simple example: add(2).
In that initial call we go to the else branch (because n is not zero) and do return 2 + add(2 - 1) (i.e. return 2 + add(1)).
That leads to the second calls, which also goes to the else branch and does return 1 + add(1 - 1) (i.e. return 1 + add(0)).
That leads to a call in which n is equal to zero and so we return zero.
That returns to the return 1 + add(1 - 1) part, which is equal to return 1 + 0 so return that.
That returns to the return 2 + add(2 - 1) part, which now is equal to return 2 + 1.
And that takes us back to the initial call, giving the result 3.
It can be laid out in a tree something like
add(2) -> return 2 + add(2 - 1)
add(1) -> return 1 + add(1 - 1)
add(0) -> return 0
add(1) -> return 1 + 0
add(2) -> return 2 + 1
Related
I tried to develop a recursive function that finds the nth term of the sequence (1,1,3,7,17,41,99,239,577,1393 ...), however, I was unsuccessful:
int progRec(int n){
return 2*progRec(n-1) + progRec(n-2);}
Any thoughts?
Add the stop condition. I assume it's 1 if n <= 2:
int progRec(int n) {
if (n <= 2) {
return 1;
}
return 2 * progRec(n - 1) + progRec(n - 2);
}
You can optimize this recursion by eliminating the second branching, which is just recalculating already visited values. Just pass the previous calculated terms as an argument:
int progRec(int n, int val = 1, int prev = 1) {
return n <= 2 ? val : progRec(n - 1, 2 * val + prev, val);
}
You can optimize it further into a for loop because now it's just a tail-recursive function.
I wanna make a funcion that will take a natural number and make a new number so every digit in the old number will be incremented and if the digit is 9 it will become zero, but not to check specificly if the digit is 9.
example:
930 will return 41
9999 will return 0
879021 will return 980132.
This is what i got so far:
int newNumber(int n)
{
int dig;
if (n < 9)
return n + 1;
dig = n % 10;
dig++;
n = n / 10;
n = n * 10 + dig;
return newNumber(n/10);
}
There are a couple of issues with your code:
It doesn't handle a single digit of 9 (which cause a stack overflow).
Adding 1 to 9 makes 10 not 0.
I've run it through the sample data you supplied and it seems to work (in C#) and it has a hard core recursive line at the end.
int newNumber(int n)
{
if (n == 9)
return 0;
if (n < 9)
return n + 1;
return (newNumber(n / 10) * 10) + newNumber(n % 10);
}
Here's to avoid the check for n == 9:
int newNumber(int n)
{
static int table[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
return (n <= 9) ? table[n] : (newNumber(n / 10) * 10) + newNumber(n % 10);
}
A lookup table seems the most appropriate and does exactly what the requirements describe. Trying to use the non-compatible arithmetic operators results in side effects (as we see in Bathsheba's answer for example), that then need to be corrected.
unsigned newNumber(unsigned n, unsigned c = 0)
{
return n ? (n + 1) % 10 + 10 * newNumber(n / 10, 1 + c) : !c;
}
is one way, and it will treat 0 as 1, via the !c branch where c counts the number of recursions. Note the tail recursion in the ternary conditional branch - some compilers will optimise a tail recursion out to a simple loop, see What is tail recursion?
Bathsheba's solution posted above is very elegant by using the ternary operator, but it will give you a wrong result if the input is zero. To avoid that you may use a stub function:
#include <stdio.h>
int incDigits(int n)
{
return n ? (n + 1) % 10 + incDigits(n / 10) * 10 : 0;
}
int newNumber(int n)
{
return n ? incDigits(n) : 1;
}
int main()
{
for(int i = 0; i <= 100; ++i)
{
int n = newNumber(i);
printf("%d -> %d\n", i, n);
}
}
EDIT: user meaning-matters also posted a way to fix the input value problem using a lookup table, but he still has to check if n equals 9, which is something you don't want. So I believe using a stub function still is the best way.
Two ternary operator has been used to take care of the two cases:
i) number equal to 9
ii) number not equal to 9 => Another ternary operator is used to take care of further two possible cases:
a) number greater than 9( return sum of num(n/10)*10 and num(n%10) ); this can be further elaborated based on the argument fed to the num function.
b)number smaller than 9(return number plus one(n+1))
Once this function is called from the main function with argument equal to the number to be transformed in the manner asked in the question, each call in line4 will undergo recursion until they pass the argument to the subsequent iteration less than or equal to 9(which leads to termination of the recursion). With basic understanding of recursion, the above para can easily be understood in context to the subroutine below.
Blockquote
int num(int n)//line1
{//line2
int t;//line3
t=(n==9?0:(n>9?num(n/10)*10+num(n%10):n+1));//line4
return t;/line5
}//line6
Blockquote
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So there is a sequence of integers, {𝑎1, 𝑎2, 𝑎3, … } , the pattern of this sequence is that 𝑎𝑛 = 𝑎𝑛−1 + (𝑛 − 1) and 𝑎1 = 1. So if the first five elements in the sequence are: {𝑎1 = 1, 𝑎2 = 1 + 1 = 2, 𝑎3 = 2 + 2 = 4, 𝑎4 = 4 + 3 = 7, 𝑎5 = 7 + 4 = 11 … } . I am trying to write a program in C to ask the user to input an integer (an) to be the position index for this sequence and calculate the value of that position in the sequence. Like the user inputs 7 and it prints that the answer is 22? I have to use recursion and honestly don't even know where to go from that...
I think I am figuring it out, but I am pretty sure this is how it should work and yet it is off by exactly 1!
#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);
}
int sum(int num)
{
if (num!=0)
return num-1 + sum(num-1); // sum() function calls itself
else
return num;
}
If I give you a function that magically calculates a(n-1), you can easily calculate a(n) right?
int a(int n)
{
int previousA /*a(n-1)*/ = magic(); // magic() knows by itself which n to use
return previousA + n - 1;
}
What if I tell you that magic() is exactly the same as a(n-1)?
int a(int n)
{
int previousA /*a(n-1)*/ = a(n-1);
return previousA + n - 1;
}
Now, the only problem is that this kind of calling we would get an endless loop of calling - for a(3), a(2) is going to be called, then a(1), a(0), a(-1)... It'll never end.
What do we do?
Happily, we have an ending condition - a(1) is constant and equal to 1.
How do we insert it into the code? We insert a condition to check if n is 1, and if it is we simply return, with no further calls.
int a(int n)
{
if (n == 1)
{
return 1;
}
else
{
int previousA /*a(n-1)*/ = a(n-1);
return previousA + n - 1;
}
}
Or in short:
int a(int n)
{
return n == 1 ? a(n - 1) + n - 1 : 1;
}
(The ? and : are the syntax for a ternary operator. Read about it if you didn't understand them.)
For starters the name sum is not suitable because nothing is summarized. Maybe the function could be named like for example recursive_sequence.
The sequence is calculated for non-negative numbers. You have the base condition a[1] == 1 and the recursive condition a[n] = a[n-1] + ( n - 1 ). You should determine the value for the index equal to 0.
You have according to the conditions
a[1] == a[0] + ( 1 - 1 )
that is
a[1] == a[0] + 0
so a[0] is equal to 1.
Having this base condition for the index 0 you can write the function
unsigned int recursive_sequence(unsigned int n)
{
return n == 0 ? 1 : n - 1 + recursive_sequence(n - 1);
}
Pay attention to that the return type and the type of the parameter should be unsigned integer type.
Here is a demonstrative program
#include <stdio.h>
unsigned int recursive_sequence(unsigned int n)
{
return n == 0 ? 1 : n - 1 + recursive_sequence(n - 1);
}
int main( void )
{
const unsigned int N = 6;
for (unsigned int i = 0; i < N; i++)
{
printf("%u: %u\n", i, recursive_sequence(i));
}
return 0;
}
Its output is
0: 1
1: 1
2: 2
3: 4
4: 7
5: 11
EDIT: When I upload the code to the automatic testing platform the program doesn't crash there - it returns the correct result, but takes too long (exceeds 5 seconds)... wtf...
For university I have to implement a function that returns the number of steps taken from the input to reach 1, by following the collatz conjecture. The conjecture is very simple - given any integer number:
1. If it is even - divide it by two (n/2)
2. If it is odd - times it by 3 and add one (n*3+1)
The conjecture is that all numbers will eventually reach 1. We don't have to prove or check this, we just need to return the steps taken for a given number.
We have done this problem before, but this time we must check much larger numbers (they specify to use long instead of int) AND use recursion. They have given us skeleton code, and asked us to implement only the function - so all of my code is contained inside
int lengthCollatz(long n) { //mycode }
The skeleton code in the main collects two input values - a and b, where a < b <100000000. It checks how many steps it takes for each number between a and b, following the collatz sequence, to reach 1, and then returns the number with the highest amount of steps taken.
The function I added seems to work perfectly fine, but at larger values (when input 2 is in the millions) it seems to crash for no reason and gives no error. I've tried changing everything to unsigned longs and even long longs to see if something is overflowing - in that case the program just gets stuck... I don't understand what's wrong, please help me diagnose the error. P.S. How can I improve the speed of these calculations? We have a limit of 5 seconds.
All of my code is inside the lengthCollatz function (and the length global variable just above it) Can you identify the problem?
#include <stdio.h>
#define MAX64 9223372036854775807L /* 2ˆ63 -1 */
int length = 0;
int lengthCollatz(long n) {
length++;
//if not 1
if(n!=1){
//if odd
if(n&1) {
lengthCollatz(n=n*3+1);
}
//if even
else {
lengthCollatz(n/=2);
}
}
//if reached n = 1
else {
//return amount of steps taken
int returnLength = length;
length = 0;
return returnLength;
}
}
int main(int argc, char *argv[])
{
int n, a, b, len=-1;
scanf ("%d %d", &a, &b);
while (a <= b) {
int l = lengthCollatz(a);
if (l > len) {
n = a;
len = l;
}
a++;
}
printf("%d\n", n);
return 0;
}
Updated function:
int lengthCollatz(long n) {
if(n==1){
//return depthRecursion;
}
else {
if(n&1) {
n=n*3+1;
}
else {
n/=2;
}
return lengthCollatz(n);
}
}
Here's one alternative version which does not segfault for the input range given by OP:
int collatz(unsigned long n)
{
if (n == 1)
return 1;
else if (n & 1)
return 1 + collatz(n * 3 + 1);
else
return 1 + collatz(n >> 1);
}
AFAICT, it works OK, but it's very slow. 29 seconds on my mediocre PC. An optimized version runs two seconds faster by not calling itself when the result can be precomputed, but that version borders on manual loop unrolling. FWIW:
int collatz(unsigned long n)
{
if (n == 1)
return 1;
if (n & 1)
return 2 + collatz((n * 3 + 1) >> 1);
// Is n dividable by 16?
if (n & 0xF == 0)
return 4 + collatz(n >> 4);
// Is n dividable by 8?
if (n & 0x7 == 0)
return 3 + collatz(n >> 3);
// Is n dividable by 4?
if (n & 0x3 == 0)
return 2 + collatz(n >> 2);
return 1 + collatz(n >> 1);
}
There are of course other ways to solve this, but to finish in five seconds? Please post the solution if you find one.
I'm trying to understand a code here. I have been trying to understand it for quite a while now and since i can't completely understand it i'm turning to you for help.
#include<stdio.h>
int sumdig(int);
int main()
{
int a, b;
a = sumdig(123);
b = sumdig(123);
printf("%d, %d\n", a, b);
return 0;
}
int sumdig(int n)
{
int s, d;
if(n!=0)
{
d = n%10;
n = n/10;
s = d+sumdig(n);
}
else
return 0;
return s;
}
I can understand that the number will continue to pass the function until it reaches to 0 and then it returns 1 because 0==0 but after it returns 3 and finishes with a 6. That I don't understand. Remember i'm new to C
The first time round, with 123, n % 10 will evaluate to 3, and n / 10 will evaluate to 12, so it will return 3 + sumdig(12). sumdig(12) will, in the same way, return 2 + sumdig(1), sumdig(1) will return 1 + sumdig(0), and sumdig(0) will return 0, at which point it will stop. So overall, it will return 3 + 2 + 1, which is the sum of the digits in 123.
it is quite a basic recursive call...
the function sumdig is called in the following order:
1.sumdig(123):
d=3
n=12
s=3+sumdig(12)
2.sumdig(12):
d=2
n=1
s=2+sumdig(1)
3.sumdig(1):
d=1
n=0
s=1+sumdig(0)
4.sumdig(0): returns 0
3. return 1+0
2. return 2+1
1.returns 3+3
and that's how you get 6.