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 Mathematical Formula in C

06.13.2014
| 1240 views |
  • submit to reddit
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)); //pembulatan kebawah         
    }
    
    printf("\n");
}

Finding Fibonacci sequence can be done by a simple logic, but here's a math formula. it can solve the case too. 


The formula :  Fn = (x1^n – x2^n) / root(5)  dengan pembulatan kebawah    where X1 and X2 are the roots of    x^2  - x - 1=0  equation         to find  X1 and X2 , we can use the following formula      So that  X1,X2  =>