Pollard's Rho Algorithm for Prime Factorization
Last Updated :
14 Aug, 2024
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:
- Two numbers x and y are said to be congruent modulo n (x = y modulo n) if
- their absolute difference is an integer multiple of n, OR,
- each of them leaves the same remainder when divided by n.
- The Greatest Common Divisor is the largest number which divides evenly into each of the original numbers.
- Birthday Paradox: The probability of two persons having same birthday is unexpectedly high even for small set of people.
- 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:
- Start with random x and c. Take y equal to x and f(x) = x2 + c.
- While a divisor isn't obtained
- Update x to f(x) (modulo n) [Tortoise Move]
- Update y to f(f(y)) (modulo n) [Hare Move]
- Calculate GCD of |x-y| and n
- If GCD is not unity
- If GCD is n, repeat from step 2 with another set of x, y and c
- 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.

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

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.

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 śi = si mod f, our sequence now has each ś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 śi, since f < n.
Now, say śi = ś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:
- Algorithm will run indefinitely for prime numbers.
- 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.
- 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.
Similar Reads
Number Theory for DSA & Competitive Programming What is Number Theory?Number theory is a branch of pure mathematics that deals with the properties and relationships of numbers, particularly integers. It explores the fundamental nature of numbers and their mathematical structures. Number theory has been studied for centuries and has deep connectio
3 min read
Number Theory (Interesting Facts and Algorithms) Questions based on various concepts of number theory and different types of number are quite frequently asked in programming contests. In this article, we discuss some famous facts and algorithms:Interesting Facts of Number Theory :1. All 4 digit palindromic numbers are divisible by 11.2. If we repe
5 min read
How to prepare for ACM - ICPC? ACM ICPC(Association for Computing Machinery - International Collegiate Programming Contest) is a worldwide annual multi-tiered programming contest being organized for over thirteen years. The contest is sponsored by IBM. This article focuses on what all topics that are important for competitive pro
7 min read
Basics of Number Theory
Program to Find GCD or HCF of Two NumbersGiven two positive integers a and b, the task is to find the GCD of the two numbers.Note: The GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. Examples:Input: a = 20, b = 28Output: 4Explanation: The factors of 20 are 1, 2, 4
12 min read
Program to find LCM of two numbersGiven two positive integers a and b. Find the Least Common Multiple (LCM) of a and b.LCM of two numbers is the smallest number which can be divided by both numbers. Input : a = 10, b = 5Output : 10Explanation : 10 is the smallest number divisible by both 10 and 5Input : a = 5, b = 11Output : 55Expla
5 min read
Factorial of a NumberGiven the number n (n >=0), find its factorial. Factorial of n is defined as 1 x 2 x ... x n. For n = 0, factorial is 1. We are going to discuss iterative and recursive programs in this post.Examples:Input: n = 5Output: 120Explanation: 5! = 5 * 4 * 3 * 2 * 1 = 120Input: n = 4Output: 24Explanation
7 min read
Print all prime factors of a given numberGiven a number n, the task is to find all prime factors of n.Examples:Input: n = 24Output: 2 2 2 3Explanation: The prime factorization of 24 is 23Ã3.Input: n = 13195Output: 5 7 13 29Explanation: The prime factorization of 13195 is 5Ã7Ã13Ã29.Approach:Every composite number has at least one prime fact
6 min read
Binomial CoefficientGiven an integer values n and k, the task is to find the value of Binomial Coefficient C(n, k).A binomial coefficient C(n, k) can be defined as the coefficient of x^k in the expansion of (1 + x)^n.A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that k objects can be
15+ min read
Program for nth Catalan NumberCatalan numbers are defined as a mathematical sequence that consists of positive integers, which can be used to find the number of possibilities of various combinations. The nth term in the sequence denoted Cn, is found in the following formula: \frac{(2n)!}{((n + 1)! n!)} The first few Catalan numb
13 min read
Euclid's lemmaWe are given two numbers x and y. We know that a number p divides their product. Can we say for sure that p also divides one of them? The answer is no. For example, consider x = 15, y = 6 and p = 9. p divides the product 15*6, but doesn't divide any of them. What if p is prime? Euclid's lemma states
1 min read
Euclidean algorithms (Basic and Extended)The Euclidean algorithm is a way to find the greatest common divisor of two positive integers. GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common prime factors.Examples:input: a = 12, b = 20Output: 4Explanatio
9 min read
Modular Arithmetic
Modular ArithmeticModular arithmetic is a system of arithmetic for numbers where numbers "wrap around" after reaching a certain value, called the modulus. It mainly uses remainders to get the value after wrap around. It is often referred to as "clock arithmetic. As you can see, the time values wrap after reaching 12
10 min read
Modular AdditionModular addition is a basic math concept used in computers and number systems. It is commonly used in areas like cryptography (data security), coding, and digital signal processing. In modular addition, you add two numbers normally, but if the result reaches a certain fixed number (called the modulu
4 min read
Modular MultiplicationGiven three integers a, b, and M, where M is the modulus. Compute the result of the modular multiplication of a and b under modulo M.((aÃb) mod M)Examples:Input: a = 5, b = 3, M = 11Output: 4Explanation: a à b = 5 à 3 = 15, 15 % 11 = 4, so the result is 4.Input: a = 12, b = 15, M = 7Output: 5Explana
6 min read
Modular DivisionGiven three positive integers a, b, and M, the objective is to find (a/b) % M i.e., find the value of (a à b-1 ) % M, where b-1 is the modular inverse of b modulo M.Examples: Input: a = 10, b = 2, M = 13Output: 5Explanation: The modular inverse of 2 modulo 13 is 7, so (10 / 2) % 13 = (10 à 7) % 13 =
13 min read
Euler's Totient FunctionGiven an integer n, find the value of Euler's Totient Function, denoted as Φ(n). The function Φ(n) represents the count of positive integers less than or equal to n that are relatively prime to n. Euler's Totient function Φ(n) for an input n is the count of numbers in {1, 2, 3, ..., n-1} that are re
10 min read
Euler's Totient function for all numbers smaller than or equal to nEuler's Totient function ?(n) for an input n is the count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. For example, ?(4) = 2, ?(3) = 2 and ?(5) = 4. There are 2 numbers smaller or equal to 4 that are relatively pri
13 min read
Modular Exponentiation (Power in Modular Arithmetic)Given three integers x, n, and M, compute (x^n) % M (remainder when x raised to the power n is divided by M).Examples : Input: x = 3, n = 2, M = 4Output: 1Explanation: 32 % 4 = 9 % 4 = 1.Input: x = 2, n = 6, M = 10Output: 4Explanation: 26 % 10 = 64 % 10 = 4.Table of Content[Naive Approach] Repeated
6 min read
Program to find remainder without using modulo or % operatorGiven two numbers 'num' and 'divisor', find remainder when 'num' is divided by 'divisor'. The use of modulo or % operator is not allowed.Examples : Input: num = 100, divisor = 7 Output: 2 Input: num = 30, divisor = 9 Output: 3 Method 1 : C++ // C++ program to find remainder without using // modulo o
9 min read
Modular multiplicative inverseGiven two integers A and M, find the modular multiplicative inverse of A under modulo M.The modular multiplicative inverse is an integer X such that:A X â¡ 1 (mod M) Note: The value of X should be in the range {1, 2, ... M-1}, i.e., in the range of integer modulo M. ( Note that X cannot be 0 as A*0 m
15+ min read
Multiplicative orderIn number theory, given an integer A and a positive integer N with gcd( A , N) = 1, the multiplicative order of a modulo N is the smallest positive integer k with A^k( mod N ) = 1. ( 0 < K < N ) Examples : Input : A = 4 , N = 7 Output : 3 explanation : GCD(4, 7) = 1 A^k( mod N ) = 1 ( smallest
7 min read
Compute nCr%p using Lucas TheoremGiven three numbers n, r and p, compute the value of nCr mod p. Examples: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6. Input: n = 1000, r = 900, p = 13 Output: 8 We strongly recommend referring below post as a prerequisite of this.Compute nCr % p | Set 1 (Introduc
12 min read
Compute nCr%p using Fermat Little TheoremGiven three numbers n, r and p, compute the value of nCr mod p. Here p is a prime number greater than n. Here nCr is Binomial Coefficient.Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6. Input: n = 6, r = 2, p = 13 Output: 2Recommended PracticenCrTry It! We h
15+ min read
Introduction to Chinese Remainder TheoremWe are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], .......................x % num[k-1] = rem[k-1] Basically, we are given k numbers which
7 min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[
11 min read
Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)Given a number 'n' and a prime 'p', find square root of n under modulo p if it exists. It may be given that p is in the form for 4*i + 3 (OR p % 4 = 3) where i is an integer. Examples of such primes are 7, 11, 19, 23, 31, ... etc,Examples: Input: n = 2, p = 7Output: 3 or 4Explanation: 3 and 4 both a
14 min read
Find Square Root under Modulo p | Set 2 (Shanks Tonelli algorithm)Given a number ânâ and a prime âpâ, find square root of n under modulo p if it exists. Examples: Input: n = 2, p = 113 Output: 62 62^2 = 3844 and 3844 % 113 = 2 Input: n = 2, p = 7 Output: 3 or 4 3 and 4 both are square roots of 2 under modulo 7 because (3*3) % 7 = 2 and (4*4) % 7 = 2 Input: n = 2,
15+ min read
Modular DivisionGiven three positive integers a, b, and M, the objective is to find (a/b) % M i.e., find the value of (a à b-1 ) % M, where b-1 is the modular inverse of b modulo M.Examples: Input: a = 10, b = 2, M = 13Output: 5Explanation: The modular inverse of 2 modulo 13 is 7, so (10 / 2) % 13 = (10 à 7) % 13 =
13 min read
Cyclic Redundancy Check and Modulo-2 DivisionCyclic Redundancy Check or CRC is a method of detecting accidental changes/errors in the communication channel. CRC uses Generator Polynomial which is available on both sender and receiver side. An example generator polynomial is of the form like x3 + x + 1. This generator polynomial represents key
15+ min read
Primitive root of a prime number n modulo nGiven a prime number n, the task is to find its primitive root under modulo n. The primitive root of a prime number n is an integer r between[1, n-1] such that the values of r^x(mod n) where x is in the range[0, n-2] are different. Return -1 if n is a non-prime number. Examples: Input : 7 Output : S
15 min read
Euler's criterion (Check if square root under modulo p exists)Given a number 'n' and a prime p, find if square root of n under modulo p exists or not. A number x is square root of n under modulo p if (x*x)%p = n%p. Examples : Input: n = 2, p = 5 Output: false There doesn't exist a number x such that (x*x)%5 is 2 Input: n = 2, p = 7 Output: true There exists a
11 min read
Using Chinese Remainder Theorem to Combine Modular equationsGiven N modular equations: A ? x1mod(m1) . . A ? xnmod(mn) Find x in the equation A ? xmod(m1*m2*m3..*mn) where mi is prime, or a power of a prime, and i takes values from 1 to n. The input is given as two arrays, the first being an array containing values of each xi, and the second array containing
12 min read
Multiply large integers under large moduloGiven an integer a, b, m. Find (a * b ) mod m, where a, b may be large and their direct multiplication may cause overflow. However, they are smaller than half of the maximum allowed long long int value. Examples: Input: a = 426, b = 964, m = 235Output: 119Explanation: (426 * 964) % 235 = 410664 % 23
7 min read
Compute n! under modulo pGiven a large number n and a prime p, how to efficiently compute n! % p?Examples : Input: n = 5, p = 13 Output: 3 5! = 120 and 120 % 13 = 3 Input: n = 6, p = 11 Output: 5 6! = 720 and 720 % 11 = 5 A Naive Solution is to first compute n!, then compute n! % p. This solution works fine when the value o
15+ min read
Wilson's TheoremWilson's Theorem is a fundamental result in number theory that provides a necessary and sufficient condition for determining whether a given number is prime. It states that a natural number p > 1 is a prime number if and only if:(p - 1)! â¡ â1 (mod p)This means that the factorial of p - 1 (the pro
2 min read
Number Theory
Introduction to Primality Test and School MethodGiven a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of the first few prime numbers are {2, 3, 5, ...}Examples : Input: n = 11Output: trueInput: n = 15Output: falseInput: n = 1Output:
10 min read
Fermat Method of Primality TestGiven a number n, check if it is prime or not. We have introduced and discussed the School method for primality testing in Set 1.Introduction to Primality Test and School MethodIn this post, Fermat's method is discussed. This method is a probabilistic method and is based on Fermat's Little Theorem.
10 min read
Primality Test | Set 3 (MillerâRabin)Given a number n, check if it is prime or not. We have introduced and discussed School and Fermat methods for primality testing.Primality Test | Set 1 (Introduction and School Method) Primality Test | Set 2 (Fermat Method)In this post, the Miller-Rabin method is discussed. This method is a probabili
15+ min read
Solovay-Strassen method of Primality TestWe have already been introduced to primality testing in the previous articles in this series. Introduction to Primality Test and School MethodFermat Method of Primality TestPrimality Test | Set 3 (MillerâRabin)The SolovayâStrassen test is a probabilistic algorithm used to check if a number is prime
13 min read
Legendre's formula - Largest power of a prime p in n!Given an integer n and a prime number p, the task is to find the largest x such that px (p raised to power x) divides n!.Examples: Input: n = 7, p = 3Output: x = 2Explanation: 32 divides 7! and 2 is the largest such power of 3.Input: n = 10, p = 3Output: x = 4Explanation: 34 divides 10! and 4 is the
6 min read
Carmichael NumbersA number n is said to be a Carmichael number if it satisfies the following modular arithmetic condition: power(b, n-1) MOD n = 1, for all b ranging from 1 to n such that b and n are relatively prime, i.e, gcd(b, n) = 1 Given a positive integer n, find if it is a Carmichael number. These numbers have
8 min read
Number Theory | Generators of finite cyclic group under additionGiven a number n, find all generators of cyclic additive group under modulo n. Generator of a set {0, 1, ... n-1} is an element x such that x is smaller than n, and using x (and addition operation), we can generate all elements of the set.Examples: Input : 10 Output : 1 3 7 9 The set to be generated
5 min read
Sum of divisors of factorial of a numberGiven a number n, we need to calculate the sum of divisors of factorial of the number. Examples: Input : 4 Output : 60 Factorial of 4 is 24. Divisors of 24 are 1 2 3 4 6 8 12 24, sum of these is 60. Input : 6 Output : 2418 A Simple Solution is to first compute the factorial of the given number, then
14 min read
GFact | 2x + 1(where x > 0) is prime if and only if x is a power of 2A number of the form 2x + 1 (where x > 0) is prime if and only if x is a power of 2, i.e., x = 2n. So overall number becomes 22n + 1. Such numbers are called Fermat Number (Numbers of form 22n + 1). The first few Fermat numbers are 3, 5, 17, 257, 65537, 4294967297, .... An important thing to note
1 min read
Sieve of EratosthenesGiven a number n, find all prime numbers less than or equal to n.Examples:Input: n = 10Output: [2, 3, 5, 7]Explanation: The prime numbers up to 10 obtained by Sieve of Eratosthenes are [2, 3, 5, 7].Input: n = 35Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]Explanation: The prime numbers up to 35 o
5 min read
Program for Goldbachâs Conjecture (Two Primes with given Sum)Goldbach's conjecture is one of the oldest and best-known unsolved problems in the number theory of mathematics. Every even integer greater than 2 can be expressed as the sum of two primes. Examples: Input : n = 44 Output : 3 + 41 (both are primes) Input : n = 56 Output : 3 + 53 (both are primes) Re
12 min read
Pollard's Rho Algorithm for Prime FactorizationGiven 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 ?nA large enough number will still
14 min read
Game Theory
Practice Problems
Rabin-Karp Algorithm for Pattern SearchingGiven two strings text and pattern string, your task is to find all starting positions where the pattern appears as a substring within the text. The strings will only contain lowercase English alphabets.While reporting the results, use 1-based indexing (i.e., the first character of the text is at po
12 min read
Measure one litre using two vessels and infinite water supplyThere are two vessels of capacities 'a' and 'b' respectively. We have infinite water supply. Give an efficient algorithm to make exactly 1 litre of water in one of the vessels. You can throw all the water from any vessel any point of time. Assume that 'a' and 'b' are Coprimes.Following are the steps
15 min read
Program to find last digit of n'th Fibonacci NumberGiven a number 'n', write a function that prints the last digit of n'th ('n' can also be a large number) Fibonacci number. Examples : Input : n = 0 Output : 0 Input: n = 2 Output : 1 Input : n = 7 Output : 3 Recommended PracticeThe Nth FibonnaciTry It! Method 1 : (Naive Method) Simple approach is to
13 min read
GCD of two numbers when one of them can be very largeGiven two numbers 'a' and 'b' such that (0 <= a <= 10^12 and b <= b < 10^250). Find the GCD of two given numbers.Examples : Input: a = 978 b = 89798763754892653453379597352537489494736 Output: 6 Input: a = 1221 b = 1234567891011121314151617181920212223242526272829 Output: 3 Solution : In
9 min read
Find Last Digit of a^b for Large NumbersYou are given two integer numbers, the base a (number of digits d, such that 1 <= d <= 1000) and the index b (0 <= b <= 922*10^15). You have to find the last digit of a^b.Examples: Input : 3 10Output : 9Input : 6 2Output : 6Input : 150 53Output : 0 After taking few examples, we can notic
9 min read
Remainder with 7 for large numbersGiven a large number as a string, find the remainder of number when divided by 7. Examples : Input : num = 1234 Output : 2 Input : num = 1232 Output : 0 Input : num = 12345 Output : 4Recommended PracticeRemainder with 7Try It! Simple Approach is to convert a string into number and perform the mod op
8 min read
Find (a^b)%m where 'a' is very largeGiven three numbers a, b and m where 1<=b,m<=10^6 and 'a' may be very large and contains upto 10^6 digits. The task is to find (a^b)%m. Examples: Input : a = 3, b = 2, m = 4 Output : 1 Explanation : (3^2)%4 = 9%4 = 1 Input : a = 987584345091051645734583954832576, b = 3, m = 11 Output: 10Recomm
15+ min read
Find sum of modulo K of first N natural numberGiven two integer N ans K, the task is to find sum of modulo K of first N natural numbers i.e 1%K + 2%K + ..... + N%K. Examples : Input : N = 10 and K = 2. Output : 5 Sum = 1%2 + 2%2 + 3%2 + 4%2 + 5%2 + 6%2 + 7%2 + 8%2 + 9%2 + 10%2 = 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 = 5.Recommended PracticeReve
9 min read
Count sub-arrays whose product is divisible by kGiven an integer K and an array arr[], the task is to count all the sub-arrays whose product is divisible by K.Examples: Input: arr[] = {6, 2, 8}, K = 4 Output: 4 Required sub-arrays are {6, 2}, {6, 2, 8}, {2, 8}and {8}.Input: arr[] = {9, 1, 14}, K = 6 Output: 1 Naive approach: Run nested loops and
15+ min read
Partition a number into two divisible partsGiven a number (as string) and two integers a and b, divide the string in two non-empty parts such that the first part is divisible by a and the second part is divisible by b. If the string can not be divided into two non-empty parts, output "NO", else print "YES" with the two parts. Examples: Input
15+ min read
Find power of power under mod of a primeGiven four numbers A, B, C and M, where M is prime number. Our task is to compute A raised to power (B raised to power C) modulo M. Example: Input : A = 2, B = 4, C = 3, M = 23Output : 643 = 64 so,2^64(mod 23) = 6 A Naive Approach is to calculate res = BC and then calculate Ares % M by modular expon
7 min read
Rearrange an array in maximum minimum form in O(1) extra spaceGiven a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on. Examples:Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}Explanation: First 7 is th
8 min read
Subset with no pair sum divisible by KGiven an array of integer numbers, we need to find maximum size of a subset such that sum of each pair of this subset is not divisible by K. Examples : Input : arr[] = [3, 7, 2, 9, 1] K = 3 Output : 3 Maximum size subset whose each pair sum is not divisible by K is [3, 7, 1] because, 3+7 = 10, 3+1 =
7 min read
Number of substrings divisible by 6 in a string of integersGiven a string consisting of integers 0 to 9. The task is to count the number of substrings which when convert into integer are divisible by 6. Substring does not contain leading zeroes. Examples: Input : s = "606". Output : 5 Substrings "6", "0", "6", "60", "606" are divisible by 6. Input : s = "48
9 min read
Miscellaneous Practice Problems