1# Easy fibonacci exercise
2# Method #1
3def fibonacci(n):
4 # 1th: 0
5 # 2th: 1
6 # 3th: 1 ...
7 if n == 1:
8 return 0
9 elif n == 2:
10 return 1
11 else:
12 return fibonacci(n - 1) + fibonacci(n - 2)
13
14# Method #2
15def fibonacci2(n):
16 if n == 0: return 0
17 n1 = 1
18 n2 = 1
19 # (1, n - 2) because start by 1, 2, 3... not 0, 1, 1, 2, 3....
20 for i in range(1, n - 2):
21 n1 += n2
22 n2 = n1 - n2
23 return n1
24
25
26print(fibonacci(13))
27# return the nth element in the fibonacci sequence
1//to find nth fibonacci number(recursive solution)
2class Solution {
3 public int fib(int n) {
4 if(n==0){
5 return 0;
6 }
7 if(n==1){
8 return 1;
9 }
10 if(n==2){
11 return 1;
12 }
13 return fib(n-1)+fib(n-2);
14 }
15}
1class Solution {
2 public int fib(int n) {
3 if(n==0){
4 return 0;
5 }
6 if(n==1){
7 return 1;
8 }
9 if(n==2){
10 return 1;
11 }
12 return fib(n-1)+fib(n-2);
13 }
14}
1// FIBONACCI SERIES
2// 0 1 1 2 3 5 8 13
3
4let number = 7;
5// let a=0,b =1,next;
6let a=-1,b=1,next;
7
8for(let i=1;i<=number;i++){
9 next= a + b;
10 a = b;
11 b = next
12 console.log(next)
13}