Skip to content

Instantly share code, notes, and snippets.

@khan5v
Created September 25, 2017 09:58
Show Gist options
  • Save khan5v/3fb0becce53e0de3b50266e84a223253 to your computer and use it in GitHub Desktop.
Save khan5v/3fb0becce53e0de3b50266e84a223253 to your computer and use it in GitHub Desktop.
Binpow - a^n % m in sublinear time
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