working fme

This commit is contained in:
Zach S-B 2021-11-05 18:02:46 +11:00
parent e5967e6e7a
commit 926c1a9b39
2 changed files with 23 additions and 23 deletions

View File

@ -33,7 +33,7 @@ public static void main(String[] args)
Q2Tools toolbox = new Q2Tools(); Q2Tools toolbox = new Q2Tools();
toolbox.fastModularExpon(5, 117, 19); System.out.println(toolbox.fastModularExpon("3785", "8395", "65537"));
} }
} }

View File

@ -21,38 +21,38 @@ public class Q2Tools {
} }
/** /**
* A^B mod C * Performs a fast modular exponation, (base^exponent)%modulus.
* @param A * Takes input values as strings containg the numbers
* @param B * @param base
* @param C * @param exponent
* @param modulus
* @return
*/ */
public BigInteger fastModularExpon(String base, String exponent, String modulus) public BigInteger fme(String base, String exponent, String modulus)
{ {
// BigInteger baseVal = new BigInteger(base); BigInteger baseVal = new BigInteger(base);
// BigInteger exponentVal = new BigInteger(exponent); BigInteger exponentVal = new BigInteger(exponent);
// BigInteger modulusVal = new BigInteger(modulus); BigInteger modulusVal = new BigInteger(modulus);
//modulusVal.equals(BigInteger.valueOf(1)); if(modulusVal.equals(BigInteger.valueOf(1)))
if(modulusVal == 1)
{ {
return BigInteger.valueOf(0); return BigInteger.valueOf(0);
} }
BigInteger temp = new BigInteger("1"); BigInteger result = new BigInteger("1");
while(exponentVal>0) while(exponentVal.compareTo(BigInteger.valueOf(0))==1)
{ {
if((exponentVal & 1)==1) if(exponentVal.and(BigInteger.valueOf(1)).compareTo(BigInteger.valueOf(1))==0)
{ {
// temp = (temp * baseVal) % modulusVal; result = result.multiply(baseVal);
temp = temp.multiply(BigInteger.valueOf(baseVal)); result = result.mod(modulusVal);
temp = temp.mod(BigInteger.valueOf(modulusVal));
} }
exponentVal = exponentVal >> 1; exponentVal = exponentVal.shiftRight(1);
baseVal = (baseVal*baseVal) % modulusVal; baseVal = (baseVal.multiply(baseVal)).mod(modulusVal);
} }
return temp; return result;
} }
} }