Saved Bookmarks
| 1. |
Write a Go program to find the nth Fibonacci number. |
|
Answer» To find the NTH Fibonacci number, we have to add the previous 2 Fibonacci numbers as shown below. fib(0)=0fib(1)=1fib(2)=1+0 = 1fib(3)=1+1 = 2fib(4)=2+1 = 3: : fib(n)=fib(n-1)+fib(n-2)Code: package mainimport "fmt"//nth fibonacci number functionfunc fibonacci(n int) int { if n < 2 { return n } return fibonacci(n-1) + fibonacci(n-2)}func MAIN() { fmt.Println(fibonacci(7))}The output of this code WOULD be: 13 |
|