[Hacker Rank] Fibonacci Modified

Fibonacci Modified

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
public static BigInteger fibonacciModified(int t1, int t2, int n) {
if(n == 1) return BigInteger.valueOf(t1);
if(n == 2) return BigInteger.valueOf(t1);
BigInteger b1 = BigInteger.valueOf(t1), b2 = BigInteger.valueOf(t2);
for(int i = 3; i <= n; i++) {
BigInteger next = b1.add(b2.pow(2));
b1 = b2;
b2 = next;
}
return b2;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/14/PS/HackerRank/fibonacci-modified/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.