The Wayback Machine - https://web.archive.org/web/20240616093331/https://www.geeksforgeeks.org/pollards-rho-algorithm-prime-factorization/
Open In App

Pollard’s Rho Algorithm for Prime Factorization

Last Updated : 21 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a positive integer n, and that it is composite, find a divisor of it.
Example:

Input: n = 12;
Output: 2 [OR 3 OR 4]

Input: n = 187;
Output: 11 [OR 17]

Brute approach: Test all integers less than n until a divisor is found. 
Improvisation: Test all integers less than ?n
A large enough number will still mean a great deal of work. Pollard’s Rho is a prime factorization algorithm, particularly fast for a large composite number with small prime factors. The Rho algorithm’s most remarkable success was the factorization of eighth Fermat number: 1238926361552897 * 93461639715357977769163558199606896584051237541638188580280321. 
The Rho algorithm was a good choice because the first prime factor is much smaller than the other one.

Concepts used in Pollard’s Rho Algorithm: 

  1. Two numbers x and y are said to be congruent modulo n (x = y modulo n) if 
    1. their absolute difference is an integer multiple of n, OR,
    2. each of them leaves the same remainder when divided by n.
  2. The Greatest Common Divisor is the largest number which divides evenly into each of the original numbers.
  3. Birthday Paradox: The probability of two persons having same birthday is unexpectedly high even for small set of people.
  4. Floyd’s cycle-finding algorithm: If tortoise and hare start at same point and move in a cycle such that speed of hare is twice the speed of tortoise, then they must meet at some point.

Algorithm: 

  1. Start with random x and c. Take y equal to x and f(x) = x2 + c.
  2. While a divisor isn’t obtained 
    1. Update x to f(x) (modulo n) [Tortoise Move]
    2. Update y to f(f(y)) (modulo n) [Hare Move]
    3. Calculate GCD of |x-y| and n
    4. If GCD is not unity 
      1. If GCD is n, repeat from step 2 with another set of x, y and c
      2. Else GCD is our answer

Illustration: 
Let us suppose n = 187 and consider different cases for different random values.

1. An Example of random values such that algorithm finds result: 
y = x = 2 and c = 1, Hence, our f(x) = x2 + 1. 
 

PollardRho1

2. An Example of random values such that algorithm finds result faster: 
y = x = 110 and ‘c’ = 183. Hence, our f(x) = x2 + 183. 
 

table

3. An Example of random values such that algorithm doesn’t find result: 
x = y = 147 and c = 67. Hence, our f(x) = x2 + 67. 
 

PollardRho3

Below is implementation of above algorithm: 

C++




/* C++ program to find a prime factor of composite using
   Pollard's Rho algorithm */
#include<bits/stdc++.h>
using namespace std;
 
/* Function to calculate (base^exponent)%modulus */
long long int modular_pow(long long int base, int exponent,
                          long long int modulus)
{
    /* initialize result */
    long long int result = 1;
 
    while (exponent > 0)
    {
        /* if y is odd, multiply base with result */
        if (exponent & 1)
            result = (result * base) % modulus;
 
        /* exponent = exponent/2 */
        exponent = exponent >> 1;
 
        /* base = base * base */
        base = (base * base) % modulus;
    }
    return result;
}
 
/* method to return prime divisor for n */
long long int PollardRho(long long int n)
{
    /* initialize random seed */
    srand (time(NULL));
 
    /* no prime divisor for 1 */
    if (n==1) return n;
 
    /* even number means one of the divisors is 2 */
    if (n % 2 == 0) return 2;
 
    /* we will pick from the range [2, N) */
    long long int x = (rand()%(n-2))+2;
    long long int y = x;
 
    /* the constant in f(x).
     * Algorithm can be re-run with a different c
     * if it throws failure for a composite. */
    long long int c = (rand()%(n-1))+1;
 
    /* Initialize candidate divisor (or result) */
    long long int d = 1; 
 
    /* until the prime factor isn't obtained.
       If n is prime, return n */
    while (d==1)
    {
        /* Tortoise Move: x(i+1) = f(x(i)) */
        x = (modular_pow(x, 2, n) + c + n)%n;
 
        /* Hare Move: y(i+1) = f(f(y(i))) */
        y = (modular_pow(y, 2, n) + c + n)%n;
        y = (modular_pow(y, 2, n) + c + n)%n;
 
        /* check gcd of |x-y| and n */
        d = __gcd(abs(x-y), n);
 
        /* retry if the algorithm fails to find prime factor
         * with chosen x and c */
        if (d==n) return PollardRho(n);
    }
 
    return d;
}
 
/* driver function */
int main()
{
    long long int n = 10967535067;
    printf("One of the divisors for %lld is %lld.",
          n, PollardRho(n));
    return 0;
}


Java




/* Java program to find a prime factor of composite using
   Pollard's Rho algorithm */
import java.util.*;
 
class GFG{
 
/* Function to calculate (base^exponent)%modulus */
static long  modular_pow(long  base, int exponent,
                          long  modulus)
{
    /* initialize result */
    long  result = 1;
 
    while (exponent > 0)
    {
        /* if y is odd, multiply base with result */
        if (exponent % 2 == 1)
            result = (result * base) % modulus;
 
        /* exponent = exponent/2 */
        exponent = exponent >> 1;
 
        /* base = base * base */
        base = (base * base) % modulus;
    }
    return result;
}
 
/* method to return prime divisor for n */
static long  PollardRho(long  n)
{
    /* initialize random seed */
    Random rand = new Random();
 
    /* no prime divisor for 1 */
    if (n == 1) return n;
 
    /* even number means one of the divisors is 2 */
    if (n % 2 == 0) return 2;
 
    /* we will pick from the range [2, N) */
    long  x = (long)(rand.nextLong() % (n - 2)) + 2;
    long  y = x;
 
    /* the constant in f(x).
     * Algorithm can be re-run with a different c
     * if it throws failure for a composite. */
    long  c = (long)(rand.nextLong()) % (n - 1) + 1;
 
    /* Initialize candidate divisor (or result) */
    long  d = 1L; 
 
    /* until the prime factor isn't obtained.
       If n is prime, return n */
    while (d == 1)
    {
        /* Tortoise Move: x(i+1) = f(x(i)) */
        x = (modular_pow(x, 2, n) + c + n) % n;
 
        /* Hare Move: y(i+1) = f(f(y(i))) */
        y = (modular_pow(y, 2, n) + c + n) % n;
        y = (modular_pow(y, 2, n) + c + n) % n;
 
        /* check gcd of |x-y| and n */
        d = __gcd(Math.abs(x - y), n);
 
        /* retry if the algorithm fails to find prime factor
         * with chosen x and c */
        if (d == n) return PollardRho(n);
    }
 
    return d;
}
   
// Recursive function to return gcd of a and b 
static long __gcd(long a, long b) 
{ 
 return b == 0? a:__gcd(b, a % b);    
}
 
/* driver function */
public static void main(String[] args)
{
    long n = 10967535067L;
    System.out.printf("One of the divisors for " + n + " is " +
          PollardRho(n));
}
}
 
// This code contributed by aashish1995


Python3




# Python 3 program to find a prime factor of composite using
# Pollard's Rho algorithm
import random
import math
 
# Function to calculate (base^exponent)%modulus
def modular_pow(base, exponent,modulus):
 
    # initialize result
    result = 1
 
    while (exponent > 0):
     
        # if y is odd, multiply base with result
        if (exponent & 1):
            result = (result * base) % modulus
 
        # exponent = exponent/2
        exponent = exponent >> 1
 
        # base = base * base
        base = (base * base) % modulus
     
    return result
 
# method to return prime divisor for n
def PollardRho( n):
 
    # no prime divisor for 1
    if (n == 1):
        return n
 
    # even number means one of the divisors is 2
    if (n % 2 == 0):
        return 2
 
    # we will pick from the range [2, N)
    x = (random.randint(0, 2) % (n - 2))
    y = x
 
    # the constant in f(x).
    # Algorithm can be re-run with a different c
    # if it throws failure for a composite.
    c = (random.randint(0, 1) % (n - 1))
 
    # Initialize candidate divisor (or result)
    d = 1
 
    # until the prime factor isn't obtained.
    # If n is prime, return n
    while (d == 1):
     
        # Tortoise Move: x(i+1) = f(x(i))
        x = (modular_pow(x, 2, n) + c + n)%n
 
        # Hare Move: y(i+1) = f(f(y(i)))
        y = (modular_pow(y, 2, n) + c + n)%n
        y = (modular_pow(y, 2, n) + c + n)%n
 
        # check gcd of |x-y| and n
        d = math.gcd(abs(x - y), n)
 
        # retry if the algorithm fails to find prime factor
        # with chosen x and c
        if (d == n):
            return PollardRho(n)
     
    return d
 
# Driver function
if __name__ == "__main__":
 
    n = 10967535067
    print("One of the divisors for", n , "is ",PollardRho(n))
     
# This code is contributed by chitranayal   


C#




/* C# program to find a prime factor of composite using
   Pollard's Rho algorithm */
using System;
class GFG
{
 
/* Function to calculate (base^exponent)%modulus */
static long  modular_pow(long  _base, int exponent,
                          long  modulus)
{
   
    /* initialize result */
    long  result = 1;
 
    while (exponent > 0)
    {
       
        /* if y is odd, multiply base with result */
        if (exponent % 2 == 1)
            result = (result * _base) % modulus;
 
        /* exponent = exponent/2 */
        exponent = exponent >> 1;
 
        /* base = base * base */
       _base = (_base * _base) % modulus;
    }
    return result;
}
 
/* method to return prime divisor for n */
static long  PollardRho(long  n)
{
   
    /* initialize random seed */
    Random rand = new Random();
 
    /* no prime divisor for 1 */
    if (n == 1) return n;
 
    /* even number means one of the divisors is 2 */
    if (n % 2 == 0) return 2;
 
    /* we will pick from the range [2, N) */
    long  x = (long)(rand.Next(0, -(int)n + 1));
    long  y = x;
 
    /* the constant in f(x).
     * Algorithm can be re-run with a different c
     * if it throws failure for a composite. */
    long  c = (long)(rand.Next(1, -(int)n));
 
    /* Initialize candidate divisor (or result) */
    long  d = 1L; 
 
    /* until the prime factor isn't obtained.
       If n is prime, return n */
    while (d == 1)
    {
       
        /* Tortoise Move: x(i+1) = f(x(i)) */
        x = (modular_pow(x, 2, n) + c + n) % n;
 
        /* Hare Move: y(i+1) = f(f(y(i))) */
        y = (modular_pow(y, 2, n) + c + n) % n;
        y = (modular_pow(y, 2, n) + c + n) % n;
 
        /* check gcd of |x-y| and n */
        d = __gcd(Math.Abs(x - y), n);
 
        /* retry if the algorithm fails to find prime factor
         * with chosen x and c */
        if (d == n) return PollardRho(n);
    }
 
    return d;
}
   
// Recursive function to return gcd of a and b 
static long __gcd(long a, long b) 
{ 
  return b == 0 ? a:__gcd(b, a % b);    
}
 
/* Driver code */
public static void Main(String[] args)
{
    long n = 10967535067L;
    Console.Write("One of the divisors for " + n + " is " +
          PollardRho(n));
}
}
 
// This code is contributed by aashish1995


Javascript




<script>
 
/* Javascript program to find a prime factor of composite using
   Pollard's Rho algorithm */
     
    /* Function to calculate (base^exponent)%modulus */
    function modular_pow(base,exponent,modulus)
    {
        /* initialize result */
        let  result = 1;
      
        while (exponent > 0)
        {
            /* if y is odd, multiply base with result */
            if (exponent % 2 == 1)
                result = (result * base) % modulus;
      
            /* exponent = exponent/2 */
            exponent = exponent >> 1;
      
            /* base = base * base */
            base = (base * base) % modulus;
        }
        return result;
    }
     
    /* method to return prime divisor for n */
    function PollardRho(n)
    {
        /* no prime divisor for 1 */
        if (n == 1)
            return n;
         
        /* even number means one of the divisors is 2 */
        if (n % 2 == 0)
            return 2;
         
        /* we will pick from the range [2, N) */
        let x=(Math.floor(Math.random() * (-n + 1) ));
        let y = x;
         
        /* the constant in f(x).
        * Algorithm can be re-run with a different c
        * if it throws failure for a composite. */
        let c= (Math.floor(Math.random() * (-n + 1)));
         
        /* Initialize candidate divisor (or result) */
        let d=1;
        /* until the prime factor isn't obtained.
        If n is prime, return n */
        while (d == 1)
        {
            /* Tortoise Move: x(i+1) = f(x(i)) */
            x = (modular_pow(x, 2, n) + c + n) % n;
      
            /* Hare Move: y(i+1) = f(f(y(i))) */
            y = (modular_pow(y, 2, n) + c + n) % n;
            y = (modular_pow(y, 2, n) + c + n) % n;
      
            /* check gcd of |x-y| and n */
            d = __gcd(Math.abs(x - y), n);
      
            /* retry if the algorithm fails to find prime factor
             * with chosen x and c */
            if (d == n) return PollardRho(n);
        }
      
        return d;
    }
     
    // Recursive function to return gcd of a and b
    function __gcd(a,b)
    {
        return b == 0? a:__gcd(b, a % b);
    }
     
    /* driver function */
    let n = 10967535067;
    document.write("One of the divisors for " + n + " is " +
          PollardRho(n));
     
     
    //  This code is contributed by avanitrachhadiya2155
     
</script>


Output: 

One of the divisors for 10967535067 is 104729

Time Complexity : O(sqrt(n)*logn)

Auxiliary Space: O(1)
How does this work? 
Let n be a composite (non-prime). Since n is composite, it has a non trivial factor f < n. In fact, there is at least one f <= ?n . 
Now suppose we have to pick two numbers x and y from the range [0, n-1]. The only time we get x = y modulo n is when x and y are identical. However, since f < ?n, there is a good chance x = y modulo f even when x and y are not identical (Birthday Paradox). 
We begin by randomly selecting x with replacement from the set {0, 1, â€Ķ, n-1} to form a sequence s1, s2, s3 â€Ķ Defining &sacute;i = si mod f, our sequence now has each &sacute;i belonging to {0, 1, â€Ķ, f-1}. Because both the sets are finite, eventually there will be a repeated integer in both. We expect to achieve the repeat earlier in &sacute;i, since f < n. 
 
Now, say &sacute;i = &sacute;j for i ? j, then, si = sj modulo d. And hence, |si – sj| will be a multiple of f. As per assumed above, n is also a multiple of f. Together this means that GCD of |si – sj| and n will be positive integral multiple of f, and also our candidate divisor d! The catch here is that we just knew there had to be some divisor of n, and we didn’t even care of its value. Once we hit si and sj (our final x and y) then each element in the sequence starting with si will be congruent modulo f to the corresponding element in the sequence starting with sj, and hence, a cycle. If we graph the sequence si, we will observe the shape of Greek letter Rho (?). 
At the heart of Rho algorithm is picking up random values and evaluating GCDs. To decrease the costly GCD calculations, we can implement the Pollard’s Rho with Floyd’s cycle detection (which can be understood with the tortoise-hare analogy where the tortoise moves through each element one at a time in order, and the hare starts at the same point but moves twice as fast as the tortoise). We shall have some polynomial f(x) for the same, start with random x0, y0 = x0, and compute xi+1 = f(xi) and yi+1 = f(f(yi)). Since we don’t know much about d, a typical choice for the polynomial is f(x) = x2 + c (modulo n) (Yes, ‘c’ is also be chosen randomly).
Note: 

  1. Algorithm will run indefinitely for prime numbers.
  2. The algorithm may not find the factors and return a failure for composite n. In that case, we use a different set of x, y and c and try again.
  3. The above algorithm only finds a divisor. To find a prime factor, we may recursively factorize the divisor d, run algorithm for d and n/d. The cycle length is typically of the order ?d.

Time Complexity analysis: 
The algorithm offers a trade-off between its running time and the probability that it finds a factor. A prime divisor can be achieved with a probability around 0.5, in O(?d) <= O(n1/4) iterations. This is a heuristic claim, and rigorous analysis of the algorithm remains open.

 



Previous Article
Next Article

Similar Reads

Pollard p-1 Algorithm
Factorizing a large odd integer, n, into its corresponding prime factors can prove to be a difficult task. A brute approach can be testing all integers less than n until a divisor is found. This proves to be very time consuming as a divisor might be a very large prime itself. Pollard p-1 algorithm is a better approach to find out prime factors of a
9 min read
Count occurrences of a prime number in the prime factorization of every element from the given range
Given three integers L, R, and P where P is prime, the task is to count the number of times P occurs in the prime factorization of all numbers in the range [L, R].Examples: Input: L = 2, R = 8, P = 2 Output: 7 ElementPrime FactorsTime 2 occurs22133042 * 2255062 * 3177082 * 2 * 23 1 + 0 + 2 + 0 + 1 + 0 + 3 = 7Input: L = 5, R = 25, P = 7 Output: 3 Na
10 min read
Trial division Algorithm for Prime Factorization
In this article, the trial division method to check whether a number is a prime or not is discussed. Given a number N, the task is to check whether the number is prime or not. Examples: Input: N = 433 Output: Prime Explanation: The only factors of 433 are 1 and 433. Therefore, it is a prime. Input: N = 1263 Output: Composite Explanation: The factor
7 min read
Count numbers in a given range having prime and non-prime digits at prime and non-prime positions respectively
Given two integers L and R, the task is to find the count of numbers in the range [L, R] having prime digits at prime positions and non-prime digits at non-prime positions. Examples: Input: L = 5, R = 22 Output: 7Explanation: The numbers 6, 8, 9, 12, 13, 15, and 17 have prime digits at prime positions and non-prime digits at non-prime positions. In
15 min read
Sum of Factors of a Number using Prime Factorization
Given a number N. The task is to find the sum of all factors of the given number N. Examples: Input : N = 12 Output : 28 All factors of 12 are: 1,2,3,4,6,12 Input : 60 Output : 168 Approach: Suppose N = 1100, the idea is to first find the prime factorization of the given number N. Therefore, the prime factorization of 1100 = 22 * 52 * 11.So, the fo
13 min read
Generating all divisors of a number using its prime factorization
Given an integer N, the task is to find all of its divisors using its prime factorization. Examples: Input: N = 6 Output: 1 2 3 6 Input: N = 10 Output: 1 2 5 10 Approach: As every number greater than 1 can be represented in its prime factorization as p1a1*p2a2*......*pkak, where pi is a prime number, k ? 1 and ai is a positive integer. Now all the
7 min read
Find the number of pairs with given GCD and LCM represented by prime factorization
Given two large number X and Y in the form of arrays as their prime factorization of size N and M. X = A[1]B[1] * A[2]B[2] * A[3]B[3] * ....... * A[N]B[N] and Y = C[1]D[1] * C[2]D[2] * C[3] D[3] * ..... * C[M]D[M], the task for this problem is to find out the number of pairs (a, b) such that LCM(a, b) is X and GCD(a, b) is Y. Since the number of pa
10 min read
Prime Factorization using Sieve O(log n) for multiple queries
We can calculate the prime factorization of a number "n" in O(sqrt(n)) as discussed here. But O(sqrt n) method times out when we need to answer multiple queries regarding prime factorization.In this article, we study an efficient method to calculate the prime factorization using O(n) space and O(log n) time complexity with pre-computation allowed.
11 min read
Mathematical Algorithms - Prime Factorization and Divisors
In the Mathematical algorithm there are two fundamental mathematical algorithms that is prime factorization and finding divisors. Prime factorization is the process of breaking down a number into its prime factors, while finding divisors involves identifying all the numbers that can evenly divide the original number. These concepts are very importa
3 min read
Wheel Factorization Algorithm
Given a number N. The task is to check if the given number is Prime Number or not.Examples: Input: N = 987 Output: Not a Prime Number Explanation: As, 987 = 3*7*47. Therefore 987 is not a prime number.Input: N = 67 Output: Prime Number Wheel Factorization Method: Wheel Factorization is the improvement of the method Sieve of Eratosthenes. For wheel
9 min read