The Fibonacci numbers are the numbers in the following integer sequence.
1 2 3 |
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …….. |
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
Go Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package main import "fmt" func fibonacci(n int) int { if n < 0 { return 0 } else if n == 1 || n == 2 { return 1 } else { return fibonacci(n-1) + fibonacci(n-2) } } func main() { /*display series*/ n := 10 t1 := 0 t2 := 1 //fmt.Printf("First %d terms: ", n) fmt.Print("First ", n, " terms: ") for i := 0; i < 10; i++ { fmt.Print(t1, " + ") sum := t1 + t2 t1 = t2 t2 = sum } /*sum fibonacci series*/ result := fibonacci(n) //recursion method fmt.Print(": ", result) } |
Output:
1 2 3 |
First 10 terms: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + : 55 |