## Tuesday, March 25, 2014

### Program to print all prime factors of a given number

Problem
Given a number n, write an efficient function to print all prime factors of n.

Example
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″.

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.

Here is c Code

```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 <= 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);
}
```

We are going in the loop till sqrt(n), because - Every composite number has at least one prime factor less than or equal to square root of itself. We have also used this approach to check if number is prime in method 1c) here. Thanks

References
geeksforgeeks,