Skip to content

Commit

Permalink
Create Fibonacci series
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored May 13, 2024
1 parent b28fa38 commit 1495916
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions Fibonacci series
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
//Fibonacci series

import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;

class GFG {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();

while(T-- > 0) {
int n = sc.nextInt();
Solution obj = new Solution();
long topDownans = obj.topDown(n);
long bottomUpans = obj.bottomUp(n);

if(topDownans != bottomUpans)
System.out.println(-1);
else
System.out.println(topDownans);
}
}
}

class Solution {
static long[] dp;
static int mod = 1000000007;

static long topDown(int n) {
dp = new long[n + 1];
Arrays.fill(dp, -1);

return fun(n);
}

static long fun(int n) {
if(n <= 1) {
return n;
}

if(dp[n] != -1) {
return dp[n];
}

return dp[n] = (fun(n - 1) + fun(n - 2)) % mod;
}

static long bottomUp(int n) {
dp = new long[n + 1];

dp[0] = 0;
dp[1] = 1;

for(int i = 2; i <= n; i++) {
dp[i] = (dp[i - 1] + dp[i - 2]) % mod;
}

return dp[n];
}
}

0 comments on commit 1495916

Please sign in to comment.