# Java Code to find Prime Factors of a Number.

The following java program finds the Prime Factors of a given number. Suppose given number is n= 15, the following steps shows how to obtain Prime Factors. Initially, the Iteration **i** starts with 2 to n. ( if n is divisible by **i** then, print **i** and you have to iterate upto n/i times ). If n is not divisible by **i**, then increment **i** by 1.

1) 15%2 !=0, so i=3

2) if 15%3 ==0, then print 3, divide the number by 3

3) 5%3 !=0, so i =4

4) 5 % 4 !=0, so i =5

5) 5%5 ==0, then print 5, divide the number by 5

So Prime Factors are 3, 5 */

package com.javaonline; import java.util.Scanner; class PrimeFactors { public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Enter any Number to find Prime Factors "); // int number=sc.nextInt(); System.out.println("Given Number is : " + number); System.out.print("Prime Factors are : " ); for (int i = 2; i <= number; i++) { while (number % i == 0) { System.out.print(i + " "); number = number / i; } } if (number < 1) System.out.println(number); } }

Running the above program will result the following output.

java PrimeFactor

Enter any Number to find Prime Factors

15

Given Number is : 15

Prime Factors are : 3 5

java PrimeFactor

Enter any Number to find Prime Factors

60

Given Number is : 60

Prime Factors are : 2 2 3 5

java PrimeFactor

Enter any Number to find Prime Factors

27

Given Number is : 27

Prime Factors are : 3 3 3

## Leave a Reply

Be the First to Comment!