|
| 1 | +package com.thealgorithms.others; |
| 2 | + |
| 3 | +import java.math.BigInteger; |
| 4 | +import java.util.Random; |
| 5 | + |
| 6 | +public class ShorAlgorithm { |
| 7 | + //trying to find the order of exponent given the base and the number |
| 8 | + private int exponent(BigInteger base, BigInteger number){ |
| 9 | + BigInteger result = BigInteger.ONE; |
| 10 | + int increment = 0; |
| 11 | + while (!result.equals(BigInteger.ONE) || increment == 0){ |
| 12 | + result = result.multiply(base).mod(number); |
| 13 | + increment++; |
| 14 | + } |
| 15 | + return increment; |
| 16 | + } |
| 17 | + |
| 18 | + //implementing the shor algorithm |
| 19 | + public void shorAlgorithm(BigInteger number){ |
| 20 | + if(number.mod(new BigInteger("2")).equals(BigInteger.ZERO)){ |
| 21 | + BigInteger p = number.divide(new BigInteger("2")); |
| 22 | + BigInteger q = new BigInteger("2"); |
| 23 | + System.out.println("p: "+ p + " q: " + q); |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + Random random = new Random(); |
| 28 | + BigInteger base = BigInteger.ZERO; |
| 29 | + do{ |
| 30 | + base = new BigInteger(number.bitLength(), random); |
| 31 | + } while (base.compareTo(BigInteger.ZERO) <= 0 || base.compareTo(number) >= 0); |
| 32 | + |
| 33 | + BigInteger hcf = base.gcd(number); |
| 34 | + if(hcf.compareTo(BigInteger.ONE) > 0){ |
| 35 | + System.out.println("p: "+ hcf + " q: " + number.divide(hcf)); |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + int result = exponent(base, number); |
| 40 | + if(result % 2 != 0) return; |
| 41 | + |
| 42 | + BigInteger congruentResult = base.modPow(BigInteger.valueOf(result/2), number); |
| 43 | + if(congruentResult.equals(number.subtract(BigInteger.ONE))) return; |
| 44 | + |
| 45 | + BigInteger p = congruentResult.add(BigInteger.ONE).gcd(number); |
| 46 | + BigInteger q = congruentResult.subtract(BigInteger.ONE).gcd(number); |
| 47 | + |
| 48 | + if(!p.equals(BigInteger.ONE) && !q.equals(BigInteger.ONE)) |
| 49 | + System.out.println("p: "+ p + " q: " + q); |
| 50 | + } |
| 51 | +} |
0 commit comments