The Wayback Machine - https://web.archive.org/web/20240926143602/https://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/
Open In App

Efficient program to print all prime factors of a given number

Last Updated : 29 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
27.25%
1.1L

Given a number n, write an efficient function to print all prime factors of n. For example, if the input number is 12, then the output should be “2 2 3”. And if the input number is 315, then the output should be “3 3 5 7”.

First Approach:

Following are the steps to find all prime factors.
1) While n is divisible by 2, print 2 and divide n by 2.
2) After step 1, n must be odd. Now start a loop from i = 3 to the square root of n. While i divides n, print i, and divide n by i. After i fails to divide n, increment i by 2 and continue.
3) If n is a prime number and is greater than 2, then n will not become 1 by the above two steps. So print n if it is greater than 2.

C++




// C++ program to print all prime factors
#include <bits/stdc++.h>
using namespace std;
 
// A function to print all prime
// factors of a given number n
void primeFactors(int n)
{
    // Print the number of 2s that divide n
    while (n % 2 == 0)
    {
        cout << 2 << " ";
        n = n/2;
    }
 
    // n must be odd at this point. So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i <= sqrt(n); i = i + 2)
    {
        // While i divides n, print i and divide n
        while (n % i == 0)
        {
            cout << i << " ";
            n = n/i;
        }
    }
 
    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        cout << n << " ";
}
 
/* Driver code */
int main()
{
    int n = 315;
    primeFactors(n);
    return 0;
}
 
// This is code is contributed by rathbhupendra


C




// C Program to print all prime factors
# include <stdio.h>
 
// A function to print all prime factors of a given number n
void primeFactors(int n)
{
    // Print the number of 2s that divide n
    while (n%2 == 0)
    {
        printf("%d ", 2);
        n = n/2;
    }
 
    // n must be odd at this point.  So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i*i <= n; i = i+2)
    {
        // While i divides n, print i and divide n
        while (n%i == 0)
        {
            printf("%d ", i);
            n = n/i;
        }
    }
 
    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        printf ("%d ", n);
}
 
/* Driver program to test above function */
int main()
{
    int n = 315;
    primeFactors(n);
    return 0;
}
 
// This is code is improved by Susobhan Akhuli


Java




// Program to print all prime factors
import java.io.*;
import java.lang.Math;
 
class GFG
{
    // A function to print all prime factors
    // of a given number n
    public static void primeFactors(int n)
    {
        // Print the number of 2s that divide n
        while (n%2==0)
        {
            System.out.print(2 + " ");
            n /= 2;
        }
 
        // n must be odd at this point.  So we can
        // skip one element (Note i = i +2)
        for (int i = 3; i <= Math.sqrt(n); i+= 2)
        {
            // While i divides n, print i and divide n
            while (n%i == 0)
            {
                System.out.print(i + " ");
                n /= i;
            }
        }
 
        // This condition is to handle the case when
        // n is a prime number greater than 2
        if (n > 2)
            System.out.print(n);
    }
 
    public static void main (String[] args)
    {
        int n = 315;
        primeFactors(n);
    }
}


Python




# Python program to print prime factors
 
import math
 
# A function to print all prime factors of
# a given number n
def primeFactors(n):
     
    # Print the number of two's that divide n
    while n % 2 == 0:
        print 2,
        n = n / 2
         
    # n must be odd at this point
    # so a skip of 2 ( i = i + 2) can be used
    for i in range(3,int(math.sqrt(n))+1,2):
         
        # while i divides n , print i and divide n
        while n % i== 0:
            print i,
            n = n / i
             
    # Condition if n is a prime
    # number greater than 2
    if n > 2:
        print n
         
# Driver Program to test above function
 
n = 315
primeFactors(n)
 
# This code is contributed by Harshit Agrawal


C#




// C# Program to print all prime factors
using System;
 
namespace prime
{
public class GFG
{    
                 
    // A function to print all prime
    // factors of a given number n
    public static void primeFactors(int n)
    {
        // Print the number of 2s that divide n
        while (n % 2 == 0)
        {
            Console.Write(2 + " ");
            n /= 2;
        }
 
        // n must be odd at this point. So we can
        // skip one element (Note i = i +2)
        for (int i = 3; i <= Math.Sqrt(n); i+= 2)
        {
            // While i divides n, print i and divide n
            while (n % i == 0)
            {
                Console.Write(i + " ");
                n /= i;
            }
        }
 
        // This condition is to handle the case when
        // n is a prime number greater than 2
        if (n > 2)
            Console.Write(n);
    }
     
    // Driver Code
    public static void Main()
    {
        int n = 315;
        primeFactors(n);
    }
 
}
}
 
// This code is contributed by Sam007


Javascript




<script>
 
// JavaScript program to print all prime factors
 
// A function to print all prime
// factors of a given number n
function primeFactors(n)
{
     
    // Print the number of 2s that divide n
    while (n % 2 == 0)
    {
        document.write(2 + " ");
        n = Math.floor(n / 2);
    }
 
    // n must be odd at this point.
    // So we can skip one element
    // (Note i = i +2)
    for(let i = 3;
            i <= Math.floor(Math.sqrt(n));
            i = i + 2)
    {
         
        // While i divides n, print i
        // and divide n
        while (n % i == 0)
        {
            document.write(i + " ");
            n = Math.floor(n / i);
        }
    }
 
    // This condition is to handle the
    // case when n is a prime number
    // greater than 2
    if (n > 2)
        document.write(n + " ");
}
 
// Driver code
let n = 315;
 
primeFactors(n);
 
// This code is contributed by Surbhi Tyagi.
 
</script>


PHP




<?php
// PHP Efficient program to print all
// prime factors of a given number
 
// function to print all prime
// factors of a given number n
function primeFactors($n)
{
     
    // Print the number of
    // 2s that divide n
    while($n % 2 == 0)
    {
        echo 2," ";
        $n = $n / 2;
    }
 
    // n must be odd at this
    // point. So we can skip
    // one element (Note i = i +2)
    for ($i = 3; $i <= sqrt($n);
                   $i = $i + 2)
    {
         
        // While i divides n,
        // print i and divide n
        while ($n % $i == 0)
        {
            echo $i," ";
            $n = $n / $i;
        }
    }
 
    // This condition is to
    // handle the case when n
    // is a prime number greater
    // than 2
    if ($n > 2)
        echo $n," ";
}
 
    // Driver Code
    $n = 315;
    primeFactors($n);
 
// This code is contributed by aj_36
?>


Output

3 3 5 7 

Time Complexity: O(sqrt(n))

In the worst case ( when either n or sqrt(n) is prime, for example: take n=11 or n=121 for both the cases for loop runs sqrt(n) times), the for loop runs for sqrt(n) times. The more number of times the while loop iterates on a number it reduces the original n, which also reduces the value of sqrt(n). Although the best case time complexity is O(log(n)), when the prime factors of n is only 2 and 3 or n is of the form (2^x*(3^y) where x>=0 and y>=0.

Auxiliary Space: O(1)

How does this work?
The steps 1 and 2 take care of composite numbers and step 3 takes care of prime numbers. To prove that the complete algorithm works, we need to prove that steps 1 and 2 actually take care of composite numbers. This is clear that step 1 takes care of even numbers. And after step 1, all remaining prime factors must be odd (difference of two prime factors must be at least 2), this explains why i is incremented by 2. 

Now the main part is, the loop runs till the square root of n not till n. To prove that this optimization works, let us consider the following property of composite numbers.

Every composite number has at least one prime factor less than or equal to the square root of itself.
This property can be proved using a counter statement. Let a and b be two factors of n such that a*b = n. If both are greater than ?n, then a.b > ?n, * ?n, which contradicts the expression “a * b = n”. 

In step 2 of the above algorithm, we run a loop and do the following in loop 
a) Find the least prime factor i (must be less than ?n,)
b) Remove all occurrences i from n by repeatedly dividing n by i.
c) Repeat steps a and b for divided n and i = i + 2. The steps a and b are repeated till n becomes either 1 or a prime number.

Related Article : 
Prime Factorization using Sieve O(log n) for multiple queries
Thanks to Vishwas Garg for suggesting the above algorithm.



Previous Article
Next Article

Similar Reads

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
Efficient program to print the number of factors of n numbers
Given an array of integers. We are required to write a program to print the number of factors of every element of the given array.Examples: Input: 10 12 14 Output: 4 6 4 Explanation: There are 4 factors of 10 (1, 2, 5, 10) and 6 of 12 and 4 of 14. Input: 100 1000 10000 Output: 9 16 25 Explanation: There are 9 factors of 100 and 16 of 1000 and 25 of
15 min read
Maximum number of prime factors a number can have with exactly x factors
Given an integer X, denoting the number of factors of a positive integer N can have. The task is to find the maximum number of distinct prime factors the number N can have. Examples: Input: X = 9 Output: 2 Explanation: Some of the possible numbers having 9 factors are: 256: 1, 2, 4, 8, 16, 32, 64, 128, 256 Number of prime factors = 1 36: 1, 2, 3, 4
6 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
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
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
Print prime factors of a given integer in decreasing order using Stack
Given an integer N, the task is to print prime factors of N in decreasing order using the stack data structure. Examples: Input: N = 34Output:17 2Explanation:The prime factors of the number 34 is 2 and 17. Input: N = 8Output: 2 Approach: The idea is to use the Stack data structure to store all the prime factors of N and in the end, print all the va
4 min read
Super Ugly Number (Number whose prime factors are in given set)
Super ugly numbers are positive numbers whose all prime factors are in the given prime list. Given a number n, the task is to find the nth Super Ugly number.It may be assumed that a given set of primes is sorted. Also, the first Super Ugly number is 1 by convention. Examples: Input : primes[] = [2, 5] n = 5 Output : 8 Super Ugly numbers with given
14 min read
Number of factors of very large number N modulo M where M is any prime number
Given a large number N, the task is to find the total number of factors of the number N modulo M where M is any prime number. Examples: Input: N = 9699690, M = 17 Output: 1 Explanation: Total Number of factors of 9699690 is 256 and (256 % 17) = 1Input: N = 193748576239475639, M = 9 Output: 8 Explanation: Total Number of factors of 9699690 is 256 an
8 min read
Product of divisors of a number from a given list of its prime factors
Given an array arr[] representing a list of prime factors of a given number, the task is to find the product of divisors of that number. Note: Since the product can be, very large printed, the answer is mod 109 + 7. Examples: Input: arr[] = {2, 2, 3} Output: 1728 Explanation: Product of the given prime factors = 2 * 2 * 3 = 12. Divisors of 12 are {
8 min read
Sum of array elements which are prime factors of a given number
Given an array arr[] of size N and a positive integer K, the task is to find the sum of all array elements which are prime factors of K. Examples: Input: arr[] = {1, 2, 3, 5, 6, 7, 15}, K = 35Output: 12Explanation: From the given array, 5 and 7 are prime factors of 35. Therefore, required sum = 5 + 7 = 12. Input: arr[] = {1, 3, 5, 7}, K = 42Output:
8 min read
Distinct Prime Factors of a given number N
Given a number N, the task is to find the distinct Prime Factors of N. Examples: Input: N = 12Output: 2 3Explanation: The factors of 12 are 1, 2, 3, 4, 6, 12.Among these the distinct prime factors are 2 and 3. Input: N = 39Output: 3 13 Approach: The approach is to use a map to check whether a given factor of the number has occurred earlier or not.
7 min read
Number which has the maximum number of distinct prime factors in the range M to N
Given two numbers M and N. The task is to print the number which has the maximum number of distinct prime factors of numbers in range M and N. If there exist multiple numbers, print the smallest one. Examples: Input: a=4, b=10 Output: 6 Number of distinct Prime Factors of 4 is 1 Number of distinct Prime Factors of 5 is 1 Number of distinct Prime Fa
10 min read
Number with maximum number of prime factors
Given an integer N. The task is to find a number that is smaller than or equal to N and has maximum prime factors. In case there are two or more numbers with the same maximum number of prime factors, find the smallest of all.Examples: Input : N = 10Output : 6Number of prime factor of:1 : 02 : 13 : 14 : 15 : 16 : 27 : 18 : 19 : 110 : 26 and 10 have
15+ 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
Prime Number Program | Code to Check whether a number is Prime or not
Given a positive integer n, write a code to check whether the number is prime. What is Prime Number? 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: true Input: n = 15Output: false Input: n = 1Output: false Tab
12 min read
Program to print factors of a number in pairs
Given a number n, the task of the programmer is to print the factors of the number in such a way that they occur in pairs. A pair signifies that the product of the pair should result in the number itself. Examples: Input : 24Output : 1*24 2*12 3*8 4*6Input : 50Output : 1*50 2*25 5*10Recommended: Please try your approach on {IDE} first, before movin
7 min read
Find and Count total factors of co-prime A or B in a given range 1 to N
Given three integers N, A, B, the task is to find the remainder when the sum of integers which are divisible by either A or B in the range [1, N] is divided by the number of integers in this range.Note: The numbers A and B are co-primes. Examples: Input: N = 88, A = 11, B = 8 Output: 8 Explanation: There are a total of 18 numbers in the range [1, 8
12 min read
Maximum Length of Sequence of Sums of prime factors generated by the given operations
Given two integers N and M, the task is to perform the following operations: For every value in the range [N, M], calculate the sum of its prime factors followed by the sum of prime factors of that sum and so on.Generate the above sequence for each array element and calculate the length of the sequence Illustration N = 8 Prime factors = {2, 2, 2}.
12 min read
Sort given Array in descending order according to highest power of prime factors
Given an array arr[] of size N. The task is to sort the elements in arr[] based to their Highest Degree of Expression, in descending order. The Highest Degree of a number is defined as the maximum value in which it can be expressed as the power of its factors. Note: If the numbers have the same degree of expression the element coming first in the o
12 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
Number less than equals to N with maximum product of prime factors
Given a number N, the task is to find the number which is less than or equals to N whose product of prime factors is maximum.Note: If there is more than one number whose maximum product is equal, then print the smallest number of them.Examples: Input: N = 12 Output: 11 Explanation: Product of prime factor of all numbers before N: 2 = 2 3 = 3 4 = 2
7 min read
Check if there exists a number with X factors out of which exactly K are prime
Given two integers X and K, the task is to determine whether there exists a number that has exactly X factors out of which K is prime.Examples: Input: X = 8, K = 1 Output: Yes Explanation: The number is 128 Factors of 128 = {1, 2, 4, 8, 16, 32, 64, 128} which are 8 in count = X Among these, only 2 is prime. Therefore count of prime factor = 1 = KIn
15+ min read
Maximum number of unique prime factors
Given a number N, find the maximum number of unique prime factors any number can have in range [1, N].Examples: Input : N = 500 Output : 4 The maximum number of prime factors for any number in [1, 500] is 4. A number in range that has 4 prime factors is 210 (2 x 3 x 5 x 7) Input : N = 3 Output : 1 Input : N = 5000 Output : 5 Recommended PracticeMax
10 min read
Number of steps to convert to prime factors
Given an array arr[] of n positive integers. Represent every number as its factors (x * y = arr[i]) [Here x or y cannot be 1] till it cannot be further represented as x*y = arr[i]. Print the number of steps required to split it till no further representations are possible. Examples: Input: 4 4 4 Output: 3 Explanation: 1st step 2 2 4 4 . 2nd step 2
12 min read
Product of unique prime factors of a number
Given a number n, we need to find the product of all of its unique prime factors. Prime factors: It is basically a factor of the number that is a prime number itself. Examples : Input: num = 10 Output: Product is 10 Explanation: Here, the input number is 10 having only 2 prime factors and they are 5 and 2. And hence their product is 10. Input : num
11 min read
Make two numbers equal by multiplying with their prime factors minimum number of times
Given two numbers X and Y, the task is to make both of them equal by repeatedly multiplying with their prime factors minimum number of times. Examples: Input: X = 36, Y = 48Output: 3Explanation: Operation 1: Choose 2(prime factor of X) and multiply with X. Now, X = 72, Y = 48.Operation 2: Choose 2(prime factor of X) and multiply with X, Now, X = 14
10 min read
Prime factors of a big number
Given a number N, print all the prime factors and their powers. Here N &lt;= 10^18Examples : Input : 250 Output : 2 1 5 3Explanation: The prime factors of 250 are 2and 5. 2 appears once in the prime factorization of and 5 is thrice in it. Input : 1000000000000000000Output : 2 18 5 18Explanation: The prime factors of 1000000000000000000are 2 and 5.
7 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