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

Pollard’s Rho Algorithm for Prime Factorization

Last Updated : 14 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
51.45%
35.3K

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

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
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
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
Shor’s Factorization Algorithm
Shor’s Factorization Algorithm: Shor’s Factorization Algorithm is proposed by Peter Shor.It suggests that quantum mechanics allows the factorization to be performed in polynomial time, rather than exponential time achieved after using classical algorithms.This could have a drastic impact on the field of data security, a concept based on the prime f
8 min read
Dixon's Factorization Method with implementation
Dixon's Factorization method is an integer factorization algorithm. In this article, this method is explained to find the factors of a composite number. Dixon Factorization is based on the well-known fact of number theory that: If [Tex]x^{2}\equiv y^{2}(mod\;n) [/Tex]with [Tex]x \neq \pm y(mod\; n) [/Tex]it is likely that gcd(x - y, n) will be fact
10 min read
Euler's Factorization method
Given a number N, the task is to find the factors of N. Examples: Input: N = 1000009 Output: 293 3413 Explanation: 293 * 3413 = 1000009Input: N = 100000 Output: 800 125 Explanation: 800 * 125 = 100000 Euler's Factorization method: Euler's factorization method works on the principle that all the numbers N which can be written as the sum of two power
15+ min read
Fermat's Factorization Method
Fermat's Factorization method is based on the representation of an odd integer as the difference of two squares. For an integer n, we want a and b such as: n = a2 - b2 = (a+b)(a-b) where (a+b) and (a-b) arethe factors of the number nExample: Input: n = 6557Output: [79,83]Explanation: For the above value, the first try for a is ceil value of square
6 min read
Prime numbers after prime P with sum S
Given three numbers sum S, prime P, and N, find all N prime numbers after prime P such that their sum is equal to S.Examples : Input : N = 2, P = 7, S = 28 Output : 11 17 Explanation : 11 and 17 are primes after prime 7 and (11 + 17 = 28) Input : N = 3, P = 2, S = 23 Output : 3 7 13 5 7 11 Explanation : 3, 5, 7, 11 and 13 are primes after prime 2.
13 min read
Sum of each element raised to (prime-1) % prime
Given an array arr[] and a positive integer P where P is prime and none of the elements of array are divisible by P. Find sum of all the elements of the array raised to the power P - 1 i.e. arr[0]P - 1 + arr[1]P - 1 + ... + arr[n - 1]P - 1 and print the result modulo P.Examples: Input: arr[] = {2, 5}, P = 3 Output: 2 22 + 52 = 29 and 29 % 3 = 2Inpu
3 min read
Print the nearest prime number formed by adding prime numbers to N
Given a number N. The task is to print the nearest prime if the number is not prime by making it prime by adding prime numbers sequentially from 2. Examples: Input: N = 8 Output: 13 8 is not prime, so add the first prime to it to get 10 10 is not prime, hence add the second prime, i.e., 3 to get 13 which is prime. Input: N = 45 Output: 47 Naive App
11 min read
Maximize difference between sum of prime and non-prime array elements by left shifting of digits minimum number of times
Given an array arr[] of size N, the task is to find the maximum difference between the sum of the prime numbers and the sum of the non-prime numbers present in the array, by left shifting the digits of array elements by 1 minimum number of times. Examples: Input: arr[] = {541, 763, 321, 716, 143}Output: Difference = 631, Count of operations = 6Expl
14 min read
Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
Given an array of positive numbers, the task is to calculate the absolute difference between sum of non-prime numbers and prime numbers. Note: 1 is neither prime nor non-prime. Examples: Input : 1 3 5 10 15 7 Output : 10 Explanation: Sum of non-primes = 25 Sum of primes = 15 Input : 3 4 6 7 Output : 0 Naive Approach: A simple solution is to travers
15+ min read
Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
Given an array of positive numbers, the task is to calculate the absolute difference between product of non-prime numbers and prime numbers.Note: 1 is neither prime nor non-prime.Examples: Input : arr[] = {1, 3, 5, 10, 15, 7} Output : 45 Explanation : Product of non-primes = 150 Product of primes = 105 Input : arr[] = {3, 4, 6, 7} Output : 3 Naive
15 min read
Check if a prime number can be expressed as sum of two Prime Numbers
Given a prime number N. The task is to check if it is possible to express N as the sum of two separate prime numbers.Note: The range of N is less than 108. Examples: Input: N = 13Output: YesExplanation: The number 13 can be written as 11 + 2, here 11 and 2 are both prime.Input: N = 11Output: NoRecommended: Please try your approach on {IDE} first, b
13 min read
Check whether the sum of prime elements of the array is prime or not
Given an array having N elements. The task is to check if the sum of prime elements of the array is prime or not. Examples: Input: arr[] = {1, 2, 3} Output: Yes As there are two primes in the array i.e. 2 and 3. So, the sum of prime is 2 + 3 = 5 and 5 is also prime. Input: arr[] = {2, 3, 2, 2} Output: No Approach: First find prime number up to 10^5
10 min read
Print prime numbers with prime sum of digits in an array
Given an array arr[] and the task is to print the additive primes in an array. Additive primes: Primes such that the sum of their digits is also a prime, such as 2, 3, 7, 11, 23 are additive primes but not 13, 19, 31 etc.Examples: Input: arr[] = {2, 4, 6, 11, 12, 18, 7} Output: 2, 11, 7 Input: arr[] = {2, 3, 19, 13, 25, 7} Output: 2, 3, 7 A simple
8 min read
Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
Given an integer N, the task is to print N integers ? 109 such that no two consecutive of these integers are co-prime and every 3 consecutive are co-prime. Examples: Input: N = 3 Output: 6 15 10Input: N = 4 Output: 6 15 35 14 Approach: We can just multiply consecutive primes and for the last number just multiply the gcd(last, last-1) * 2. We do thi
15+ min read
Print all numbers whose set of prime factors is a subset of the set of the prime factors of X
Given a number X and an array of N numbers. The task is to print all the numbers in the array whose set of prime factors is a subset of the set of the prime factors of X. Examples: Input: X = 60, a[] = {2, 5, 10, 7, 17} Output: 2 5 10 Set of prime factors of 60: {2, 3, 5} Set of prime factors of 2: {2} Set of prime factors of 5: {5} Set of prime fa
13 min read
Sum of prime numbers without odd prime digits
Given an integer N. The task is to find the sum of the first N prime numbers which don't contain any odd primes as their digit.Some of such prime numbers are 2, 11, 19, 29, 41 ...... Examples: Input : N = 2 Output : 13 2 + 11 = 13Input : N = 7 Output : 252 Approach : We first use a Sieve of Eratosthenes to store all prime numbers.Next check for eac
8 min read
Absolute difference between the XOR of Non-Prime numbers and Prime numbers of an Array
Given an array arr[] of N positive integers, the task is to calculate the absolute difference between XOR of non-prime numbers and prime numbers. Note that 1 is neither prime nor composite.Examples: Input: arr[] = {1, 3, 5, 10, 15, 7} Output: 4 Xor of non-primes = 10 ^ 15 = 5 Xor of primes = 3 ^ 5 ^ 7 = 1 |5 - 1| = 4Input: arr[] = {3, 4, 6, 7} Outp
8 min read
Permutation of first N positive integers such that prime numbers are at prime indices
Given an integer N, the task is to find the number of permutations of first N positive integers such that prime numbers are at prime indices (for 1-based indexing).Note: Since, the number of ways may be very large, return the answer modulo 109 + 7. Examples: Input: N = 3 Output: 2 Explanation: Possible permutation of first 3 positive integers, such
6 min read
Permutation of first N positive integers such that prime numbers are at prime indices | Set 2
Given an integer N, the task is to find the number of permutations of first N positive integers such that prime numbers are at prime indices (for 1-based indexing).Note: Since, the number of ways may be very large, return the answer modulo 109 + 7.Examples: Input: N = 3 Output: 2 Explanation: Possible permutation of first 3 positive integers, such
6 min read
Count prime pairs whose difference is also a Prime Number
Given an integer N, the task is to count the number of pairs of prime numbers in the range [1, N] such that the difference between elements of each pair is also a prime number. Examples: Input: N = 5 Output: 2 Explanations: Pair of prime numbers in the range [1, 5] whose difference between elements is also a prime number are: (2, 5) = 3 (Prime numb
9 min read
Count numbers in a given range whose count of prime factors is a Prime Number
Given a 2D array Q[][] of size N * 2 representing queries of the form {L, R}. For each query, the task is to print the count of numbers in the range [L, R] with a count of prime factors equal to a prime number. Examples: Input: Q[][] = {{4, 8}, {30, 32}} Output: 3 2 Explanation: Query 1: Prime factors of 4 = {2, 2} and count of prime factors = 2 Pr
15 min read
Count distinct prime triplets up to N such that sum of two primes is equal to the third prime
Given an integer N, the task is to count the number of distinct prime triplets (a, b, c) from the range [1, N] such that a &lt; b &lt; c ? N and a + b = c.Note: Two prime tuples are distinct if at least one of the primes present in them are different. Examples: Input: N = 6Output: 1Explanation: Among numbers in the range [1, 6], the only prime trip
6 min read
Find prime factors of Z such that Z is product of all even numbers till N that are product of two distinct prime numbers
Given a number N (N &gt; 6), the task is to print the prime factorization of a number Z, where Z is the product of all numbers ≤ N that are even and can be expressed as the product of two distinct prime numbers. Example: Input: N = 6Output: 2→1 3→1Explanation: 6 is the only number ≤ N, which is even and a product of two distinct prime numbers (2 an
7 min read