Created
September 25, 2017 09:58
-
-
Save khan5v/3fb0becce53e0de3b50266e84a223253 to your computer and use it in GitHub Desktop.
Binpow - a^n % m in sublinear time
This file contains 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
public class Utils { | |
public static long mulmod(long a, long b, long mod) { | |
return (a * b) % mod; | |
} | |
public static long binpow(long a, long pow, long mod) { | |
if (pow == 0) | |
return 1; | |
long res = binpow(a, pow / 2, mod); | |
res = mulmod(res, res, mod); | |
if (pow % 2 == 1) | |
res = mulmod(res, a, mod); | |
return res; | |
} | |
public static void main(String[] args) { | |
int i = 6; | |
long pow = 10; | |
long mod = 10; | |
long temp = i; | |
for(int j = 1; j < pow; j++) { | |
temp *= i; | |
temp = temp % mod; | |
} | |
System.out.println(temp); | |
System.out.println(binpow(i, pow, mod)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment