-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFibonacci.java
More file actions
40 lines (29 loc) · 922 Bytes
/
Fibonacci.java
File metadata and controls
40 lines (29 loc) · 922 Bytes
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
import java.math.BigInteger;
import java.util.Scanner;
public class Fibonacci {
private static BigInteger calc_fib(int n) {
BigInteger a = BigInteger.ZERO;
BigInteger b = BigInteger.ONE;
for (int bit = Integer.highestOneBit(n); bit != 0; bit >>>= 1) {
BigInteger d = multiply(a, b.shiftLeft(1).subtract(a));
BigInteger e = multiply(a, a).add(multiply(b, b));
a = d;
b = e;
if ((n & bit) != 0) {
BigInteger c = a.add(b);
a = b;
b = c;
}
}
return a;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.close();
System.out.println(calc_fib(n));
}
private static BigInteger multiply(BigInteger x, BigInteger y) {
return x.multiply(y);
}
}