Write a Java program to print all prime factors of a given number
This Java program takes an integer input from the user and finds its prime factors using a loop. Here's how it works:
- The program prompts the user to input a number using the System.out.print method and reads the input using the Scanner class.
- The program checks if the input is greater than 0. If it is not, the program does not proceed with the prime factorization.
- The program checks if the input is divisible by 2. If it is, it prints 2 as a prime factor and divides the input by 2.
- The program then checks for other prime factors using a for loop. The loop starts from 3 and goes up to the square root of the input (since any factor larger than the square root would have a corresponding factor smaller than the square root). The loop increments by 2 (since any even factor would have already been divided by 2 in step 3).
- Inside the loop, the program checks if the input is divisible by the current loop variable. If it is, the program prints the loop variable as a prime factor and divides the input by the loop variable.
- After the loop is finished, the program checks if the input is greater than 2 (since any remaining factor must be a prime number larger than 2). If it is, the program prints the input as a prime factor.
Source Code
import java.util.*;
class PrimeFactors
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.print("Input a number: ");
int n = scan.nextInt();
if (n>0)
{
while (n%2==0)
{
System.out.println(2);
n /= 2;
}
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
while (n%i == 0)
{
System.out.println(i);
n /= i;
}
}
if (n > 2)
System.out.print(n);
}
}
}
Output
Input a number: 10
2
5