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.
Adding to @RogerFernandezGuri's excellent answer, a possibly more readable answer in Go for printing a Fibonacci series.
package main
import "fmt"
func main() {
a, b := 0, 1
h := func() int {
a, b = b, a+b
return b-a
}
fibonacci := func() func() int { return h }
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f()) //0, 1, 1, 2, 3, 5, 8, 13, 21, 34
}
}
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.
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!