Monday 29 April 2013

FIBONACCI SERIES


The Fibonacci Sequence is a very interesting and fast growing series.

You can find each term by adding two preceding terms of the sequence provided that the first two terms are 0 and 1;
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 
610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 
28657, 46368, 75025, 121393, 196418, 317811, ...
The next number is found by adding up the two numbers before it.
  • The 2 is found by adding the two numbers before it (1+1)
  • Similarly, the 3 is found by adding the two numbers before it (1+2),
  • And the 5 is (2+3),
  • and so on!
Here I have two different programs for finding the nth term of fibonacci series.
In the first program you can find the nth fibonacci term with the limitations of range. But to fix this limitation I have a very interesting program, which can find even the 50th fibonacci term. 

First program:-
/***************************************************************/
#include<stdio.h>
#include<conio.h>

int main()
{
int num,i;
double a=0,b=1,c;
clrscr();
printf("ENTER THE TERM NUMBER : ");
scanf("%d",&num);

for(i=0;i<num;i++)
{
c=a+b;
if(i==num-3)
{
printf("%0.0lf",c);
break;
}
a=b;
b=c;
}
getch();
return 1;
}


/***************************************************************/




Program 2:-
/***************************************************************/
#include<stdio.h>
#include<conio.h>
#define max 2000

int arr1[max],arr2[max],arr3[max];

void fun(void);

int main()
{
int num,i,j,tag=0;
clrscr();
for(i=0;i<max;i++)
arr1[i]=arr2[i]=arr3[i]=0;

arr2[max-1]=1;

printf("ENTER THE TERM : ");
scanf("%d",&num);

for(i=0;i<num;i++)
{
fun();

if(i==num-3)
break;

for(j=0;j<max;j++)
arr1[j]=arr2[j];

for(j=0;j<max;j++)
arr2[j]=arr3[j];

}

for(i=0;i<max;i++)
{
if(tag||arr3[i])
{
tag=1;
printf("%d",arr3[i]);
}
}


getch();
return 1;
}

void fun(void)
{
int i,temp;
for(i=0;i<max;i++)
arr3[i]=arr1[i]+arr2[i];

for(i=max-1;i>0;i--)
{
if(arr3[i]>9)
{
temp=arr3[i];
arr3[i]%=10;
arr3[i-1]+=(temp/10);
}
}
}

/***************************************************************/


Note that the second program gives accurately the 100th term of series. 
Though the first program also gives some value but it is not correct. It gives correct values only upto certain limited terms.

1 comment: