|
| 1 | +package com.thealgorithms.maths; |
| 2 | + |
| 3 | +/* |
| 4 | + * Java program for pollard rho algorithm |
| 5 | + * The algorithm is used to factorize a number n = pq, |
| 6 | + * where p is a non-trivial factor. |
| 7 | + * Pollard's rho algorithm is an algorithm for integer factorization |
| 8 | + * and it takes as its inputs n, the integer to be factored; |
| 9 | + * and g(x), a polynomial in x computed modulo n. |
| 10 | + * In the original algorithm, g(x) = ((x ^ 2) − 1) mod n, |
| 11 | + * but nowadays it is more common to use g(x) = ((x ^ 2) + 1 ) mod n. |
| 12 | + * The output is either a non-trivial factor of n, or failure. |
| 13 | + * It performs the following steps: |
| 14 | + * x ← 2 |
| 15 | + * y ← 2 |
| 16 | + * d ← 1 |
| 17 | +
|
| 18 | + * while d = 1: |
| 19 | + * x ← g(x) |
| 20 | + * y ← g(g(y)) |
| 21 | + * d ← gcd(|x - y|, n) |
| 22 | +
|
| 23 | + * if d = n: |
| 24 | + * return failure |
| 25 | + * else: |
| 26 | + * return d |
| 27 | +
|
| 28 | + * Here x and y corresponds to xi and xj in the previous section. |
| 29 | + * Note that this algorithm may fail to find a nontrivial factor even when n is composite. |
| 30 | + * In that case, the method can be tried again, using a starting value other than 2 or a different g(x) |
| 31 | + * |
| 32 | + * Wikipedia: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm |
| 33 | + * |
| 34 | + * Author: Akshay Dubey (https://github.com/itsAkshayDubey) |
| 35 | + * |
| 36 | + * */ |
| 37 | +public class PollardRho { |
| 38 | + |
| 39 | + /** |
| 40 | + * This method returns a polynomial in x computed modulo n |
| 41 | + * |
| 42 | + * @param base Integer base of the polynomial |
| 43 | + * @param modulus Integer is value which is to be used to perform modulo operation over the polynomial |
| 44 | + * @return Integer (((base * base) - 1) % modulus) |
| 45 | + */ |
| 46 | + static int g(int base,int modulus) { |
| 47 | + return ((base * base) - 1) % modulus; |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * This method returns a non-trivial factor of given integer number |
| 52 | + * |
| 53 | + * @param number Integer is a integer value whose non-trivial factor is to be found |
| 54 | + * @return Integer non-trivial factor of number |
| 55 | + * @throws RuntimeException object if GCD of given number cannot be found |
| 56 | + */ |
| 57 | + static int pollardRho(int number) { |
| 58 | + int x = 2, y = 2, d = 1; |
| 59 | + while(d == 1) { |
| 60 | + //tortoise move |
| 61 | + x = g(x, number); |
| 62 | + |
| 63 | + //hare move |
| 64 | + y = g(g(y, number), number); |
| 65 | + |
| 66 | + //check GCD of |x-y| and number |
| 67 | + d = GCD.gcd(Math.abs(x - y), number); |
| 68 | + } |
| 69 | + if(d == number) { |
| 70 | + throw new RuntimeException("GCD cannot be found."); |
| 71 | + } |
| 72 | + return d; |
| 73 | + } |
| 74 | +} |
0 commit comments