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();
toolbox.fastModularExpon(5, 117, 19);
System.out.println(toolbox.fastModularExpon("3785", "8395", "65537"));
}
}

View File

@ -20,39 +20,39 @@ public class Q2Tools {
}
/**
* A^B mod C
* @param A
* @param B
* @param C
*/
public BigInteger fastModularExpon(String base, String exponent, String modulus)
/**
* Performs a fast modular exponation, (base^exponent)%modulus.
* Takes input values as strings containg the numbers
* @param base
* @param exponent
* @param modulus
* @return
*/
public BigInteger fme(String base, String exponent, String modulus)
{
// BigInteger baseVal = new BigInteger(base);
// BigInteger exponentVal = new BigInteger(exponent);
// BigInteger modulusVal = new BigInteger(modulus);
BigInteger baseVal = new BigInteger(base);
BigInteger exponentVal = new BigInteger(exponent);
BigInteger modulusVal = new BigInteger(modulus);
//modulusVal.equals(BigInteger.valueOf(1));
if(modulusVal == 1)
if(modulusVal.equals(BigInteger.valueOf(1)))
{
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;
temp = temp.multiply(BigInteger.valueOf(baseVal));
temp = temp.mod(BigInteger.valueOf(modulusVal));
result = result.multiply(baseVal);
result = result.mod(modulusVal);
}
exponentVal = exponentVal >> 1;
baseVal = (baseVal*baseVal) % modulusVal;
exponentVal = exponentVal.shiftRight(1);
baseVal = (baseVal.multiply(baseVal)).mod(modulusVal);
}
return temp;
return result;
}
}