Is there a better code for printing fibonacci series?

ashwin murthy

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;
}        
Roger Fernandez Guri

Also to have a more efficient way to calculate Go if you watch closely, you'll see the following sequence:

1 1 2 3 5 8 13 21 34 55 89 144 ...

The formula for mapping the Fibonacci sequence is:

Then if you code this (Go):

package main

import "fmt"

func fibonacci() func() int {
    first, second := 0, 1
    return func() int {
        ret := first
        first, second = second, first+second
        return ret
    }
}

func main() {
    f := fibonacci()
    for i := 0; i < 100; i++ {
        fmt.Println(f())
    }
}

You'll see the numbers till 100 and without using conditionals for base cases. I hope that approach helped you understand better the problem!

Cheers!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related