DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Im a freelance developer for Web apps and Artificial intelligence (in Python). Budy K. has posted 4 posts at DZone. You can read more from them at their website. View Full User Profile

Finding Fibonacci With Both Simple Logic and Mathematical Formula in C

06.11.2014
| 819 views |
  • submit to reddit
1. Simple Logic

int fibonaci(int n){

    int i,next,a=0,b=1;
    for(i=0;i<n;++i){
    
        if(i<=1){
            next = i;
        }else{
            
            next = a + b;
            a = b;
            b= next;
        }
        
        printf("%d ",next);
    }
}

2. Mathematical Formula

int fibonaci(int n){
    
    int i;float tmp;
    
    //x^2 - x - 1 =0
    float x1 = ( 1 + sqrt(5) ) / 2;
    float x2 = (1 - sqrt(5) ) / 2;  
    
    for(i=0;i<n;i++){
               
        tmp = (pow(x1,i) - pow(x2,i)) / sqrt(5);
        printf("%d ",(int)floor(tmp)); //rounding down         
    }
    
    printf("\n");
}

To find Fibonacci sequence, mathematically there're several ways Like Recursif function and using the Golder Ratio or X^2 - X - 1 = 0 Equation. 

  

Above is a recursif function which can be calculated like this

According to the formula, we have initial values for F(0) = 0, F(1) =1 

So for n > 1 , we have smth like this:

F(2) = F(2-1) + F(2-2)     
     = F(1)   + F(0) 
     = 1 + 0 = 1   
ans so on....for the next n so it will finally form the sequence


0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

but mosth people dont like Recurif.

We have another Options to do that 

1. Use just a simple Logic (see the code) 

2. Or use the formula 

Fibonacci numbers can also be found by this formula 

    Fn = (x1n – x2n) / root(5)  , where Fn is rounded down    Where X1 and X2 are roots of the    X^2  - X - 1 = 0  Equation          To find X1 and X2 , we can use this formula      So that X1,X2  =>      then we only need to form the formula into Code   for each X1, X2 , we can set variables 

    float x1 = ( 1 + sqrt(5) ) / 2;

    float x2 = (1 - sqrt(5) ) / 2;  


That's it. 


Further Fibonacci + Faktorial + Prime Code