As stated above attempting to work out which of the following two programs is most efficient for finding the nth Fibonacci number and why.
The Fibonacci numbers are numbers in the sequence: 1, 1, 2, 3, 5, 8... where each number after the first two is the sum of the preceding two numbers.
//// iteration ////
int main()
{
int n;
int t1 = 0;
int t2 = 1;
int i;
int new_term;
printf("Enter N :");
scanf("%d", &n);
if (n == 1)
new_term = 0;
else if (n == 2)
new_term = 1;
else
{
for (i = 3; i <= n; i++)
{
new_term = t1 + t2;
t1 = t2;
t2 = new_term;
}
}
printf("%dth term of the series is %d", n, new_term);
return 0;
}
//// induction ////
int fibo(int n);
int main() {
int n;
printf("Enter n : ");
scanf("%d", &n);
printf("The %dth term of Fibonacci sequence is %d", n, fibo(n));
return 0;
}
int fibo(int n)
{
if (n == 1) return 0;
if (n == 2) return 1;
return fibo(n - 1) + fibo(n - 2);
}