Untitled
unknown
plain_text
2 years ago
1.1 kB
5
Indexable
public static void main(String[] args) { int n = 5, r = 2, p = 7; // output = 3 // With Factorial Starts // Formula :: n!/ ( r! * (n-r)! ) int nf = factorial(n); int rf = factorial(r); int nrf = factorial(n - r); int ansFact = (nf / (rf * nrf)) % p; System.out.println("Factorial :: " + ansFact); // With Factorial Ends // With Fast Power Starts // Formula :: (n! %p) * ((r ^ p-2) %p) * (( (n-r) ^ p-2) %p) ) nf = factorial(n); rf = fastPower(r, p - 2, p); nrf = fastPower((n - r), p - 2, p); int ansFastpower = ((nf % p) * ((rf * nrf) % p)); System.out.println("Fast Power :: " + ansFastpower); // With Fast Power Ends } private static int fastPower(int N, int Pow, int mod) { if (Pow == 0) { return 1; } if ((Pow & 1) == 1) { return ((N % mod) * (fastPower(((N * N) % mod), (Pow / 2), mod))) % mod; } else { return (fastPower(((N * N) % mod), (Pow / 2), mod)); } } public static int factorial(int A) { if (A <= 1) { return 1; } return A * factorial(A - 1); }
Editor is loading...