Skip to main content

C Program To Find The Nth Fibonacci Number.

In Fibonacci series, each number is the sum of the two preceding numbers. For example: 0, 1, 1, 2, 3, 5, 8, ….., ∞ (infinity). The following programs return the nth number entered by user residing in the Fibonacci series.

Method 1 (Using recursion): Time Complexity: T(n) = T(n-1) + T(n-2) which is exponential, i.e. this implementation does a lot of repeated work. Extra Space: O(n) if we consider the function call stack size, otherwise O(1).

#include<stdio.h>

int fib(int n) {
if ( n <= 1 )
return n;
return fib(n-1) + fib(n-2);
}

int main () {
int n ;

printf(" Enter Number to Compute nth Fibonacci Series: ");
scanf("%d",&n);
printf("\n\n %dth term of Fibonacci Series is %d\n",n, fib(n));

return 0;
}

Method 2 (Using Dynamic Programming): We can avoid the repeated work done in the method 1 by storing the Fibonacci numbers calculated so far. Time Complexity: O(n), Extra Space: O(n).

#include<stdio.h>

int fib(int n) {
int f[n+1];
int i;

f[0] = 0;
f[1] = 1;

for (i = 2; i <= n; i++) {
f[i] = f[i-1] + f[i-2];
}
return f[n];
}

int main () {
int n ;

printf(" Enter Number to Compute nth Fibonacci Series: ");
scanf("%d",&n);
printf("\n\n %dth term of Fibonacci Series is %d\n",n, fib(n));

return 0;
}

Method 3 (Optimizing Method 2): We can optimize the space used in method 2 by storing the previous two numbers only because that is all we need to get the next Fibonacci number in series. Time Complexity: O(n), Extra Space: O(1).

#include<stdio.h>

int fib(int n) {
int a = 0, b = 1, c, i;

if( n == 0)
return a;

for (i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}

int main () {
int n ;

printf(" Enter Number to Compute nth Fibonacci Series: ");
scanf("%d",&n);
printf("\n\n %dth term of Fibonacci Series is %d\n",n, fib(n));

return 0;
}

Method 4 (Using power of the matrix {{1,1},{1,0}} ): If we multiply n times the matrix M = {{1,1},{1,0}} to itself (in another words calculate power(M, n )), then we get the (n+1)th Fibonacci number as the element at row and column (0, 0) in the resultant matrix. Time Complexity: O(n), Extra Space: O(1).

#include <stdio.h>

void multiply(int F[2][2], int M[2][2]);
void power(int F[2][2], int n);

int fib(int n) {
int F[2][2] = {{1,1},{1,0}};

if (n == 0)
return 0;
power(F, n-1);

return F[0][0];
}

void multiply(int F[2][2], int M[2][2]) {
int x =  F[0][0]*M[0][0] + F[0][1]*M[1][0];
int y =  F[0][0]*M[0][1] + F[0][1]*M[1][1];
int z =  F[1][0]*M[0][0] + F[1][1]*M[1][0];
int w =  F[1][0]*M[0][1] + F[1][1]*M[1][1];

F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}

void power(int F[2][2], int n) {
int i;
int M[2][2] = {{1,1},{1,0}};

for (i = 2; i <= n; i++)
multiply(F, M);
}

int main () {
int n ;

printf(" Enter Number to Compute nth Fibonacci Series: ");
scanf("%d",&n);
printf("\n\n %dth term of Fibonacci Series is %d\n",n, fib(n));

return 0;
}

Method 5 (Optimizing Method 4): We can do recursive multiplication to get power(M, n) in the previous method. Time Complexity: O(log n), Extra Space: O(log n) if we consider the function call stack size, otherwise O(1).

#include <stdio.h>

void multiply(int F[2][2], int M[2][2]);
void power(int F[2][2], int n);

int fib(int n) {
int F[2][2] = {{1,1},{1,0}};

if (n == 0)
return 0;
power(F, n-1);
return F[0][0];
}

void power(int F[2][2], int n) {
if( n == 0 || n == 1)
return;

int M[2][2] = {{1,1},{1,0}};

power(F, n/2);
multiply(F, F);

if (n%2 != 0)
multiply(F, M);
}

void multiply(int F[2][2], int M[2][2]) {
int x =  F[0][0]*M[0][0] + F[0][1]*M[1][0];
int y =  F[0][0]*M[0][1] + F[0][1]*M[1][1];
int z =  F[1][0]*M[0][0] + F[1][1]*M[1][0];
int w =  F[1][0]*M[0][1] + F[1][1]*M[1][1];

F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}

int main () {
int n ;

printf(" Enter Number to Compute nth Fibonacci Series: ");
scanf("%d",&n);
printf("\n\n %dth term of Fibonacci Series is %d\n",n, fib(n));

return 0;
}

Popular posts from this blog

C++ Program To Implement Bank Management System.

#include<iostream> #include<fstream> #include<cctype> #include<iomanip> #include <cstdlib> using namespace std; class account { int acno; char name[50]; int deposit; char type; public: void create_account(); //function to get data from user void show_account() const; //function to show data on screen void modify(); //function to add new data void dep(int); //function to accept amount and add to balance amount void draw(int); //function to accept amount and subtract from balance amount void report() const; //function to show data in tabular format int retacno() const; //function to return account number int retdeposit() const; //function to return balance amount char rettype() const;  //function to return type of account }; void account::create_account() { cout<<"\nEnter The Account No. : "; cin>>acno; cout<<"\n\nEnter The Name Of The Account Holder : "; cin.ig...

The Basics Of C Programming - Part 3.

There are a number of different C input commands, the most useful of which is the scanf command. To read a single integer value into the variable called a you can use: scanf("%d",&a); When the program reaches the scanf statement it pauses to give the user time to type something on the keyboard and continues only when users press Enter or Return, to signal that he, or she, has finished entering the value. Then the program continues with the new value stored in a. In this way, each time the program is run the user gets a chance to type in a different value to the variable and the program also gets the chance to produce a different result! The final missing piece in the jigsaw is using the printf function, the one we use to print the value currently being stored in a variable. To display the value stored in the variable a you can use: printf("The value stored in a is %d",a); Note: the scanf function does not prompt for an input. You should ge...

C Program To Check Whether A Number Is Palindrome Or Not.

This program takes an integer from user and the integer is reversed. If the reversed integer is equal to the integer entered by user then that number is a palindrome. If not that number is not a palindrome.   #include <stdio.h> int main()  { int num, temp, remainder, reverse = 0; printf("Enter an integer: "); scanf("%d", &num); /*  original number is stored at temp */ temp = num; while (num > 0)  { remainder = num % 10; reverse = reverse * 10 + remainder; num /= 10;   }

C Program To Convert Natural Numbers To Roman Numerals.

Roman Number System of representing numbers devised by the ancient Romans. The numbers are formed by combinations of the symbols I, V, X, L, C, D, and M, standing, respectively, for 1, 5, 10, 50, 100, 500, and 1,000 in the Hindu-Arabic numeral system. Natural numbers mean no negative numbers and no fractions, i.e. the whole numbers from 1 upwards: 1, 2, 3, and so on. Here is source code of the C program to convert natural numbers to Roman Numerals. It compiles and runs on any operating system. #include <stdio.h> void predigit(char num1, char num2); void postdigit(char c, int n); char romanval[1000]; int i = 0; int main() { int j; long number; printf("Enter any natural number: "); scanf("%d", &number);