Skip to content
Related Articles

Related Articles

Pollard p-1 Algorithm

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 09 Sep, 2022
View Discussion
Improve Article
Save Article

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 any integer. Using the combined help of Modular Exponentiation and GCD, it is able to calculate all the distinct prime factors in no time.

Algorithm

  • Given a number n. Initialize a = 2, i = 2
  • Until a factor is returned do a <- (a^i) mod n d <- GCD(a-1, n) if 1 < d < n then     return d else     i <- i+1
  • Other factor, d’ <- n/d
  • If d’ is not prime     n <- d’     goto 1 else     d and d’ are two prime factors.

In the above algorithm, the power of ‘a’ is continuously raised until a factor, ‘d’, of n is obtained. Once d is obtained, another factor, ‘d”, is n/d. If d’ is not prime, the same task is repeated for d’ Examples:

Input : 1403
Output : Prime factors of 1403 are 61 23.
Explanation : n = 1403, a = 2, i = 2

1st Iteration:
    a = (2^2) mod 1403 = 4
    d = GCD(3, 1403) = 1
    i = 2 + 1 = 3

2nd Iteration:
    a = (4^3) mod 1403 = 64
    d = GCD(63, 1403) = 1
    i = 3 + 1 = 4

3rd Iteration:
    a = (64^4) mod 1403 = 142
    d = GCD(141, 1403) = 1
    i = 4 + 1 = 5

4th Iteration:
    a = (142^5) mod 1403 = 794
    d = GCD(793, 1403) = 61

Since 1 < d < n, one factor is 61.
d' = 1403 / 61 = 23.


Input : 2993
Output : Prime factors of 2993 are 41 73.

Below is the implementation. 

C++




// C++ code for Pollard p-1
// factorization Method
#include <bits/stdc++.h>
using namespace std;
  
//  function for
// calculating GCD
int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
// function for
// checking prime
bool isPrime(int n)
{
    if (n <= 1)
        return false;
    if (n == 2 || n == 3)
        return true;
    if (n % 2 == 0)
        return false;
    for (int i = 3; i * i <= n; i += 2)
        if (n % i == 0)
            return false;
    return true;
}
    
// function to generate
// prime factors
int pollard(int n)
{
    // defining base
    long long a = 2;
    
    // defining exponent
    int i = 2;
    
    // iterate till a prime factor is obtained
    while(true)
    {
         
        // recomputing a as required
        a = ((long long) pow(a, i)) % n;
        a += n;
        a %= n;
         
        // finding gcd of a-1 and n
        // using math function
        int d = gcd(a-1,n);
    
        // check if factor obtained
        if (d > 1)
        {
            //return the factor
            return d;
            break;
        }
         
        // else increase exponent by one
        // for next round
        i += 1;
    }
}
   
// Driver code
int main()
{
    
    int n = 1403;
        
    // temporarily storing n
    int num = n;
        
    // list for storing prime factors
    vector<int> ans;
        
    // iterated till all prime factors
    // are obtained
    while(true)
    {
        // function call
        int d = pollard(num);
        
        // add obtained factor to list
        ans.push_back(d);
        
        // reduce n
        int r = (num/d);
        
        // check for prime
        if(isPrime(r))
        {
            // both prime factors obtained
            ans.push_back(r);
            break;
        }
        // reduced n is not prime, so repeat
        else
      
            num = r;
    }
       
    // print the result
    cout << "Prime factors of " << n << " are ";
     
    for (int elem : ans)
        cout << elem << " ";
}
 
// This code is contributed by phasing17

Java




// Java code for Pollard p-1
// factorization Method
import java.util.*;
 
class GFG
{
  //  function for
  // calculating GCD
  static long gcd(long a, long b)
  {
    if (a == 0)
      return b;
    return gcd(b % a, a);
  }
 
  // function for
  // checking prime
  static boolean isPrime(long n)
  {
    if (n <= 1)
      return false;
    if (n == 2 || n == 3)
      return true;
    if (n % 2 == 0)
      return false;
    for (long i = 3; i * i <= n; i += 2)
      if (n % i == 0)
        return false;
    return true;
  }
 
  // function to generate
  // prime factors
  static long pollard(long n)
  {
    // defining base
    long a = 2;
 
    // defining exponent
    long i = 2;
 
    // iterate till a prime factor is obtained
    while(true)
    {
 
      // recomputing a as required
      a = ((long) Math.pow(a, i)) % n;
      a += n;
      a %= n;
 
      // finding gcd of a-1 and n
      // using math function
      long d = gcd(a-1,n);
 
      // check if factor obtained
      if (d > 1)
      {
        //return the factor
        return d;
      }
 
      // else increase exponent by one
      // for next round
      i += 1;
    }
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    long n = 1403;
 
    // temporarily storing n
    long num = n;
 
    // list for storing prime factors
    ArrayList<Long> ans = new ArrayList<Long>();
 
    // iterated till all prime factors
    // are obtained
    while(true)
    {
      // function call
      long d = pollard(num);
 
      // add obtained factor to list
      ans.add(d);
 
      // reduce n
      long r = (num/d);
 
      // check for prime
      if(isPrime(r))
      {
        // both prime factors obtained
        ans.add(r);
        break;
      }
      // reduced n is not prime, so repeat
      else
 
        num = r;
    }
 
    // prlong the result
    System.out.print("Prime factors of " + n + " are ");
 
    for (long elem : ans)
      System.out.print(elem + " ");
  }
}
 
// This code is contributed by phasing17

Python3




# Python code for Pollard p-1
# factorization Method
    
# importing "math" for
# calculating GCD
import math
    
# importing "sympy" for
# checking prime
import sympy
    
       
# function to generate
# prime factors
def pollard(n):
    
    # defining base
    a = 2
    
    # defining exponent
    i = 2
    
    # iterate till a prime factor is obtained
    while(True):
    
        # recomputing a as required
        a = (a**i) % n
    
        # finding gcd of a-1 and n
        # using math function
        d = math.gcd((a-1), n)
    
        # check if factor obtained
        if (d > 1):
    
            #return the factor
            return d
    
            break
    
        # else increase exponent by one
        # for next round
        i += 1
   
# Driver code
n = 1403
    
# temporarily storing n
num = n
    
# list for storing prime factors
ans = []
    
# iterated till all prime factors
# are obtained
while(True):
    
    # function call
    d = pollard(num)
    
    # add obtained factor to list
    ans.append(d)
    
    # reduce n
    r = int(num/d)
    
    # check for prime using sympy
    if(sympy.isprime(r)):
    
        # both prime factors obtained
        ans.append(r)
    
        break
    
    # reduced n is not prime, so repeat
    else:
    
        num = r
   
# print the result
print("Prime factors of", n, "are", *ans)

C#




// C# code for Pollard p-1
// factorization Method
using System;
using System.Collections.Generic;
 
class GFG
{
  //  function for
  // calculating GCD
  static long gcd(long a, long b)
  {
    if (a == 0)
      return b;
    return gcd(b % a, a);
  }
 
  // function for
  // checking prime
  static bool isPrime(long n)
  {
    if (n <= 1)
      return false;
    if (n == 2 || n == 3)
      return true;
    if (n % 2 == 0)
      return false;
    for (long i = 3; i * i <= n; i += 2)
      if (n % i == 0)
        return false;
    return true;
  }
 
  // function to generate
  // prime factors
  static long pollard(long n)
  {
    // defining base
    long a = 2;
 
    // defining exponent
    long i = 2;
 
    // iterate till a prime factor is obtained
    while(true)
    {
 
      // recomputing a as required
      a = ((long) Math.Pow(a, i)) % n;
      a += n;
      a %= n;
 
      // finding gcd of a-1 and n
      // using math function
      long d = gcd(a-1,n);
 
      // check if factor obtained
      if (d > 1)
      {
        //return the factor
        return d;
      }
 
      // else increase exponent by one
      // for next round
      i += 1;
    }
  }
 
  // Driver code
  public static void Main(string[] args)
  {
 
    long n = 1403;
 
    // temporarily storing n
    long num = n;
 
    // list for storing prime factors
    List<long> ans = new List<long>();
 
    // iterated till all prime factors
    // are obtained
    while(true)
    {
      // function call
      long d = pollard(num);
 
      // add obtained factor to list
      ans.Add(d);
 
      // reduce n
      long r = (num/d);
 
      // check for prime
      if(isPrime(r))
      {
        // both prime factors obtained
        ans.Add(r);
        break;
      }
      // reduced n is not prime, so repeat
      else
 
        num = r;
    }
 
    // prlong the result
    Console.Write("Prime factors of " + n + " are ");
 
    foreach (long elem in ans)
      Console.Write(elem + " ");
  }
}
 
// This code is contributed by phasing17

Javascript




// JavaScript code for Pollard p-1
// factorization Method
    
//  function for
// calculating GCD
function gcd(x, y)
{
    x = Math.abs(x);
  y = Math.abs(y);
  while(y) {
    var t = y;
    y = x % y;
    x = t;
  }
  return x;
}
 
// function for
// checking prime
function isPrime(n)
{
    if (n <= 1)
        return false;
    if (n == 2 || n == 3)
        return true;
    if (n % 2 == 0)
        return true;
    for (var i = 3; i * i <= n; i += 2)
        if (n % i == 0)
            return false;
    return true;
}
    
       
// function to generate
// prime factors
function pollard(n)
{
    // defining base
    let a = 2
    
    // defining exponent
    let i = 2
    
    // iterate till a prime factor is obtained
    while(true)
    {
    
        // recomputing a as required
        a = (a**i) % n
    
        // finding gcd of a-1 and n
        // using math function
        d = gcd((a-1), n)
    
        // check if factor obtained
        if (d > 1)
        {
            //return the factor
            return d
    
            break
        }
        // else increase exponent by one
        // for next round
        i += 1
    }
}
   
// Driver code
let n = 1403
    
// temporarily storing n
let num = n
    
// list for storing prime factors
let ans = []
    
// iterated till all prime factors
// are obtained
while(true)
{
    // function call
    let d = pollard(num)
    
    // add obtained factor to list
    ans.push(d)
    
    // reduce n
    r = Math.floor(num/d)
    
    // check for prime
    if(isPrime(r))
    {
        // both prime factors obtained
        ans.push(r)
    
        break
    }
    // reduced n is not prime, so repeat
    else
    
        num = r
}
   
// print the result
console.log("Prime factors of", n, "are", ans.join(" "))
 
// This code is contributed by phasing17

Output:

Prime factors of 1403 are 61 23

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!