Skip to content

Instantly share code, notes, and snippets.

@cciollaro
Created October 17, 2013 23:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cciollaro/7034206 to your computer and use it in GitHub Desktop.
Save cciollaro/7034206 to your computer and use it in GitHub Desktop.
A right-to-left binary modular exponentiation algorithm in java i.e. calculating a^b mod n
public class ModExp {
public static void main(String[] args) {
System.out.println(modExp(4,13,497));
}
public static int modExp(int a, int b, int n){
int d = 1;
String k = Integer.toBinaryString(b);
for(int i = 1; i <= k.length(); i++){
if(k.charAt(k.length()-i) == '1'){
d = (d*a) % n;
}
a = (a*a) % n;
}
return d;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment