Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

c - Is there a better code for printing fibonacci series?

Is the algorithm below the best way of generating the Fibonacci series? Or is there a better approach?

This is my C program to print fibonacci series.

#include<stdio.h>
int main()
{
    int a,i,n,t;
    printf("Enter the number");
    scanf("%d",&a);

    i=1;
    n=0;

    for(t=1;t<=a;t++)
    {
        n=n+i;
        i=n-i;
        printf("%d",n);
    }

    return 0;
}        
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is optimal in terms of time complexity and space complexity, and much faster than the naive recursive algorithm, which is exponential in terms of run time.

It does look as though your assignments in your loop aren't quite right, though. You want

int oldi = i;
i = n+i;
n = oldi;

HOWEVER, your approach has a crucial weakness, which is that you will quickly overflow the bounds of an int. Even with a 64-bit value, you'll get wrong answers by the time you hit f(100).

To get correct answers with arbitrary indices, you will need an arbitrary size integer library.

A related issue came up yesterday with calculating the Fibonacci series in Go.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...