From e5967e6e7a95c9a67767d74853b618278f83b048 Mon Sep 17 00:00:00 2001 From: Zach S-B Date: Fri, 5 Nov 2021 17:30:18 +1100 Subject: [PATCH] Bigint --- Q2Tools.java | 49 +++++++++++++++++++++++-------------------------- 1 file changed, 23 insertions(+), 26 deletions(-) diff --git a/Q2Tools.java b/Q2Tools.java index 17c54c0..de77b3a 100644 --- a/Q2Tools.java +++ b/Q2Tools.java @@ -26,36 +26,33 @@ public class Q2Tools { * @param B * @param C */ - public void fastModularExpon(int A, int B, int C) + public BigInteger fastModularExpon(String base, String exponent, String modulus) { - String bInBinary = Integer.toBinaryString(B); - - double test = 1; + // BigInteger baseVal = new BigInteger(base); + // BigInteger exponentVal = new BigInteger(exponent); + // BigInteger modulusVal = new BigInteger(modulus); - { - int k = 0; - //Loop through the Binary String, starting from the right - for(int i = bInBinary.length()-1; i >= 0; i--) - { - - if(bInBinary.charAt(i)=='1') - { - System.out.println("Loop: "+k); - double step1 = Math.pow(2, k); - System.out.println("STEP1: "+step1); - - double step2 = Math.pow(A, step1)%C; - System.out.println("STEP2: "+step2); - test= test*step2; - - } - k++; - } + //modulusVal.equals(BigInteger.valueOf(1)); + if(modulusVal == 1) + { + return BigInteger.valueOf(0); } - - System.out.println(test); + BigInteger temp = new BigInteger("1"); - System.out.println(Math.pow(5, 64)%19); + while(exponentVal>0) + { + if((exponentVal & 1)==1) + { + // temp = (temp * baseVal) % modulusVal; + temp = temp.multiply(BigInteger.valueOf(baseVal)); + temp = temp.mod(BigInteger.valueOf(modulusVal)); + + } + + exponentVal = exponentVal >> 1; + baseVal = (baseVal*baseVal) % modulusVal; + } + return temp; } }