Write a Program to print Prime factors in java


This Java program finds the prime factors of a given number entered by the user. Prime factors are the factors of a number that are prime numbers. The program starts by importing the Scanner class, which allows the program to read input from the user.

The program then creates an instance of the Scanner class and prompts the user to enter a number. The program reads the input number using the nextInt() method of the Scanner class and stores it in the integer variable num.

Next, the program enters a for loop that runs from 2 to one less than the value of the input number (num). Within the loop, the program checks if the current loop variable (i) is a factor of the input number by checking if num is divisible by i using the modulo operator (%). If i is a factor of num, the program prints the value of i to the console and updates the value of num to be num divided by i.

The program then repeats the above process for all prime factors of the input number. If the value of num is still greater than 2 after all prime factors have been found, the program prints the value of num to the console. Finally, the program ends.

Source Code

import java.util.Scanner;
class Prime_Factors
{
   public static void main(String args[])
   {
      Scanner input = new Scanner(System.in);
      System.out.print("Enter The number :");
      int num = input.nextInt();     
      for(int i = 2; i< num; i++) {
         while(num%i == 0) {
            System.out.println(i+" ");
            num = num/i;
         }
      }
      if(num >2) {
         System.out.println(num);
      }
   }
}
 

Output

Enter The number :12
2
2
3

Example Programs