jayati

Nth Fibonacci Number

Jan 23rd, 2024
1,205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. //{ Driver Code Starts
  2. // Initial Template for C++
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. // } Driver Code Ends
  7. // User function Template for C++
  8. class Solution {
  9.   const int mod = 1000000007;
  10.   public:
  11.     int fib(int n , vector<int>&dp){
  12.         if(dp[n]!=-1)return dp[n];
  13.         else return dp[n] = ((fib(n-2,dp)%mod + fib(n-1,dp)%mod)%mod);
  14.     }
  15.     int nthFibonacci(int n){
  16.         // code here
  17.          vector<int>dp(n+1,-1);
  18.         dp[1]=1;
  19.         dp[2]=1;
  20.         return fib(n,dp);
  21.     }
  22. };
  23.  
  24. //{ Driver Code Starts.
  25. int main() {
  26.     int t;
  27.     cin >> t;
  28.     while (t--) {
  29.         int n;
  30.         cin >> n;
  31.         Solution ob;
  32.         cout << ob.nthFibonacci(n) << endl;
  33.     }
  34.     return 0;
  35. }
  36.  
  37. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment