Java Programs

Find Prime Factor of a given number

We will learn to write a Java program to find the prime factor of a given program.

Before we start writing the program, we should know what a prime factor is

How will this Java program behave?

The program for calculating prime factors takes a number as input and outputs all outputs with prime factors as result.

For example, if you want to calculate the prime factor of a number 12, then you should enter 12 as input.

And after the calculation the program should return 2, 2, 3 as output.

Program:

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 
2,2,3

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs