-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFibonacci series
62 lines (48 loc) · 1.26 KB
/
Fibonacci series
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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];
}
}