Efficient Program To Print All Prime Factors of A Given Number

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Efficient program to print all prime factors of a given number

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

We strongly recommend that you click here and practice it, before
moving on to the solution.
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 square root of n. While i divides n, print i
and
divide
n
by
i,
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 above two steps. So print
n if it is greater than 2.

C/C++
Java
// Program to print all prime factors
# include <stdio.h>
# include <math.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;
}

+2)

// n must be odd at this point.

So we can skip one element (Note i = i

for (int i = 3; i <= sqrt(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 whien 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;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy