Answers for "nth fibonacci number"

0

find nth fibonacci number

// a dynamic programming approach for generating any number of fibonacci number
#include<bits/stdc++.h>
using namespace std;
 
long long int save[100]; // declare any sized array
long long int fibo(int n){
  if(n==0) return 0;
  if(n==1) return 1;
  if(save[n]!=-1) return save[n]; //if save[n] holds any value that means we have already calculated it and can return it to recursion tree
  save[n]=fibo(n-1)+fibo(n-2); // if it come tp this line that means I don't know what is the value of it
  return save[n];
}

int main(){
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  memset(save,-1,sizeof save);
  cout<<fibo(2)<<'\n';

  return 0;
}
Posted by: Guest on March-15-2022
0

nth fibonacci number

def fib(n):
    if(n<0):
        print("Invalid input")
    elif(n==0):
        return 0
    elif(n==1) or (n==2):
        return 1
    else:
        return fib(n-1)+fib(n-2)
n=int(input())
print(fib(n))
Posted by: Guest on March-01-2022

Code answers related to "nth fibonacci number"

Browse Popular Code Answers by Language