Created
October 17, 2013 23:36
-
-
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
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
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