Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C
Tip/Trick

Finding Fibonacci With Mathematical Formula in C

Rate me:
Please Sign up or sign in to vote.
4.60/5 (3 votes)
12 Jun 2014CPOL 13.3K   1   11
Finding Fibonacci sequence can be done by a simple logic, but we can solve it too with a Math formula

Introduction

Finding Fibonacci sequence can be done by a simple logic:

C++
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);
    }
}

But here's a math formula. It can solve the case too.

The formula : Fn = (x1n – x2n) / root(5) (Fn is rounded down)
where X1 and X2 are the roots of x2 - x - 1=0 equation
to find X1 and X2 , we can use the following formula:

So that X1,X2 =>

C++
int fibonaci(int n){
   
    int i;float tmp;
   
    //x2 - 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");
}

Output: 0 1 1 2......so on

Of course, we don't need to use the math formula in programming, this is just an example.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer SDP
Indonesia Indonesia
Freelance Web developer, Artificial Intelligence and Science enthusiast

Comments and Discussions

 
QuestionThe Golden Ratio Pin
andreas proteus16-Jun-14 7:40
andreas proteus16-Jun-14 7:40 
AnswerRe: The Golden Ratio Pin
stevic16-Jun-14 18:37
professionalstevic16-Jun-14 18:37 
QuestionMissing figures Pin
Amarnath S12-Jun-14 23:13
professionalAmarnath S12-Jun-14 23:13 
AnswerRe: Missing figures Pin
stevic12-Jun-14 23:20
professionalstevic12-Jun-14 23:20 
GeneralRe: Missing figures Pin
Amarnath S13-Jun-14 0:37
professionalAmarnath S13-Jun-14 0:37 
GeneralRe: Missing figures Pin
stevic13-Jun-14 0:45
professionalstevic13-Jun-14 0:45 
GeneralRe: Missing figures Pin
Amarnath S13-Jun-14 1:21
professionalAmarnath S13-Jun-14 1:21 
GeneralRe: Missing figures Pin
stevic13-Jun-14 1:25
professionalstevic13-Jun-14 1:25 
GeneralRe: Missing figures Pin
Amarnath S13-Jun-14 2:00
professionalAmarnath S13-Jun-14 2:00 
GeneralRe: Missing figures Pin
Amarnath S15-Jun-14 18:12
professionalAmarnath S15-Jun-14 18:12 
GeneralRe: Missing figures Pin
stevic15-Jun-14 18:28
professionalstevic15-Jun-14 18:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.