Created
January 17, 2022 14:37
-
-
Save AnasAboreeda/7aa2a181224d81df70b72944548d6125 to your computer and use it in GitHub Desktop.
Fibonacci Number modulo M
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.math.BigInteger; | |
import java.util.*; | |
public class FibonacciHuge { | |
public static long getFibonacciHugeNaive(long n, long m) { | |
if (n <= 1) return n; | |
BigInteger previous = BigInteger.ZERO; | |
BigInteger current = BigInteger.ONE; | |
for (long i = 0; i < n - 1; ++i) { | |
BigInteger tmpPrevious = previous; | |
previous = current; | |
current = tmpPrevious.add(current); | |
} | |
return current.mod(BigInteger.valueOf(m)).longValue(); | |
} | |
public static long getFibonacciHugeFast(long n, long m) { | |
long pisanoNo = getPisanoPeriod(m); | |
n = pisanoNo > 0 ? n % pisanoNo : n; | |
return getFibonacci(n).mod(BigInteger.valueOf(m)).longValue(); | |
} | |
public static long getPisanoPeriod(long m) { | |
long prev = 0; | |
long curr = 1; | |
long res = 0; | |
for (long i = 0; i < m * m; i++) { | |
long temp = curr; | |
curr = (prev + curr) % m; | |
prev = temp; | |
if (prev == 0 && curr == 1) { | |
return i + 1; | |
} | |
} | |
return res; | |
} | |
private static BigInteger getFibonacci(long n) { | |
if (n <= 1) { | |
return BigInteger.valueOf(n); | |
} | |
BigInteger prev = BigInteger.ZERO; | |
BigInteger curr = BigInteger.ONE; | |
for (int i = 2; i <= n; i++) { | |
BigInteger temp = curr; | |
curr = prev.add(curr); | |
prev = temp; | |
} | |
return curr; | |
} | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
long n = scanner.nextLong(); | |
long m = scanner.nextLong(); | |
System.out.println(getFibonacciHugeFast(n, m)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment