We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Recursion: Fibonacci Numbers
- Discussions
Recursion: Fibonacci Numbers
Recursion: Fibonacci Numbers
+ 0 comments Basic code using python
def fibonacci(n): # Write your code here. a=0 b=1 k.append(a) k.append(b) while(n+2>0): c=a+b a=b b=c k.append(c) n-=1 n = int(input()) k=[] fibonacci(n) print(k[n])
+ 0 comments in swift. I made it through 2D array
func fibo(_ n: Int, _ memo: inout [Int: [Int]]) -> Int { if n < 2 { return n } if let values = memo[n] { return values[0] + values[1] } let value1 = fibo(n - 2, &memo) let value2 = fibo(n - 1, &memo) memo[n] = [value1, value2] return value1 + value2 } func fibonacci (n: Int) -> Int { var memo = [Int: [Int]]() return fibo(n, &memo) } // read the integer n let n = Int(readLine()!)! // print the nth fibonacci number print(fibonacci(n: n))
+ 0 comments This solution is optimized solution which O(n) time and space complexity; For more easy solution of 30 Day of Coding challenges visit this page: https://github.com/deepak14ri/Competitive-Code-Solutions/
const fibonacci = (n, memo = []) => { if(n in memo) return memo[n]; if(n<=2) return 1; memo[n] = fibonacci(n-1, memo)+fibonacci(n-2, memo); return memo[n]; } fibonacci(2);
+ 0 comments def fibonacci(n): fb = [0]*(n+1) fb[0] = 0 fb[1] = 1 for i in range(2, n+1): fb[i] = fb[i-1] + fb[i-2] return fb[n] n = int(input()) print(fibonacci(n))
+ 0 comments php
function fibonacci($n, $result = [0,1]) { if (isset($result[$n])) { return $result[$n]; } $length = count($result); $result[] = $result[$length - 1] + $result[$length - 2]; return fibonacci($n, $result); }
Load more conversations
Sort 291 Discussions, By:
Please Login in order to post a comment