In this tutorial you will learn writing Java program to find prime factor of a given program.

Before moving on writing program lets know what is prime factor?

**Read This:** Prime factor program in C

## How this Java program will behave?

The prime factor calculation program will take a number as a input and in result it will print all outputs with prime factors.

**For example**

If you want to calculate the prime factor of a number 12 then you should give 12 as an input.

And After calculation program should return 2, 2, 3 as an output.

## Program : Find all Prime Factor of a given number in Java

```
import java.util.*;
class Main{
public static void main(String ...args){
int i=0;
Scanner sc= new Scanner(System.in);
System.out.print("please enter a number: ");
int n= sc.nextInt();
System.out.print("Prime factors of a given number n = ");
while(n % 2 == 0) {
System.out.print(2+",");
n = n/2;
}
for(i = 3; i <= Math.sqrt(n); i=i+2){
while(n % i == 0) {
System.out.print(i+",");
n = n/i;
}
}
if(n > 2) {
System.out.print(n+",");
}
}
}
```

**Output:**

```
please enter a number: 12
Prime factors of a given number n = 2,2,3,
```

## Conclusion

In the above tutorial we have seen the implementation of a Java program to find the prime factors of a given number. Before going into the coding, the concept of prime factors was briefly introduced. In the above program we are taking user input and printing the prime factors as an output.

We have used loop to iteratively divide the number by its smallest prime factors, starting from 2 and then checking odd numbers up to the square root of the remaining quotient. The final result is a list of prime factors printed as output.

For example, we have taking 12 as an input and output is 2, 2, 3, as a prime factor.

This simple yet effective Java program provides a practical demonstration of prime factorization, an essential concept in number theory. Understanding and implementing such programs contribute to a foundational grasp of programming logic and mathematical concepts in the Java programming language.

Hope you have liked this tutorial.

Happy Coding!!