Reputation: 33
given that 1, 2, 5, 26, 677,... such that the nth term of the series equals to (n-1)th ^2 +1 and the first term of the series is 1. Write a program using recursive function named f to compute the nth term.
I can't get anything to print out. How can i Fix this?
#include <stdio.h>
#include <math.h>
int f(int n)
{
if(n==1)
{
return 1;
}
else
{
return f((n-1)^2)+1;
}
}
int main()
{
int N,i;
printf("Enter the number of terms: ");
scanf("%d",&N);
int u = f(N);
for(i=0;i<N;i++)
{
printf("%d ",u);
}
return 0;
}```
Upvotes: 0
Views: 165
Reputation: 212248
The most direct way (IMO) to do this is something like:
#include <stdio.h>
#include <stdlib.h>
long
f(int n)
{
return n == 1 ? 1 : f(n-1) * f(n-1) + 1;
}
int
main(int argc, char **argv)
{
int n = argc > 1 ? strtol(argv[1], NULL, 10) : 2;
for(int i=1; i < n; i++) {
printf("%d: %ld\n", i, f(i));
}
return 0;
}
There are a lot of improvements that should be made above, but that gives the basic idea. But it seems like you're trying to do something more along the lines of:
#include <stdio.h>
#include <stdlib.h>
long
f(int n)
{
long r= 1;
if(n > 1) {
r = f(n-1);
r = r * r + 1 ;
}
printf("%d: %ld\n", n, r);
return r;
}
int
main(int argc, char **argv)
{
int n = argc > 1 ? strtol(argv[1], NULL, 10) : 2;
f(n);
return 0;
}
You should probably include some error checking to prevent overflow and return non-zero from main if that happens, but that will depend on how you want to handle overflow.
Upvotes: 1