# Print Prime Factors of A Number in Java

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 Java.

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

## 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

## Java Program To Print Prime Factors of A Number

Input:

` n = 315`

Output:

`3 3 5 7`

```// Java Program to print prime factors

import java.io.*;
import java.lang.Math;

class TechDecodeTutorials {
// 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);
}
}
```

#### Ethix

I'm a coding geek interested in cyberspace who loves to write and read