# Print Prime Factors of A Number in C++

Confronting with numbers is the first thing each one of us has learned in school. However, as we step up high more and more difficult questions based on the same fundamentals seem to appear in our way. It’s the same with programming, using the same fundamentals to find solutions for multiple complex problems. Now the cool thing is, you can be creative in your way eventually coming up with a unique solution. And if you’re able to do this, then you’ve clearly understood how to use programming for others and your good. But keeping that aside, we’ve talked about numbers before. So what if we find prime factors numbers, seems too easy right!. So let’s quickly find out how to Print Prime Factors Of A Number in C++.

With the help of this program, you will be able to find the root square of integers. Practicing these types of questions also helps to get an upper edge in Competitive Programming.

## What’s The Approach?

- We know that for each number there are unique prime factors, i.e unique set of prime numbers multiplied together give a different output. The most important aspect of maintaining this unique property of prime factorizations is that the number one, 1, be categorized as neither prime nor composite.

- Let us consider n be the integer we have to print prime factors of. So to do so firstly, we’ll
**divide**`n`

by 2 and print it till it’s divisible by 2.

- After the above instruction n will become odd, so now we’ll
**iterate a new loop****starting from 3 till the square root of n**with an**increment of 2.**In this same loop**while i divides n, print i, and divide n by i**

- Finally,
**if n is a prime number greater than 2 we’ll simply print n.**Till this step, we’ll have all the possible prime factors of input number n.

**Also Read: Print Cube Root of A Number in Python **

## C++ Program To Print Prime Factors of A Number

**Input:**

** n = 315**

**Output:**

`3 3 5 7`

// Program to print all prime factors # include <iostream> # include <math.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<<"%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) { 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 program to test above function */ int main() { int n = 315; primeFactors(n); return 0; }