Generate Prime Factors in Java

Write a program to input a positive integer, and display all the prime factors of that number.

Prime Factors are any of the prime numbers that multiply to get the original number.

Example 1:
INPUT: 24
OUTPUT: 2, 2, 2, 3

Example 2:
INPUT: 60
OUTPUT: 2, 2, 3, 5

import java.io.*;
class PrimeFactors{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("N = ");
        int n = Math.abs(Integer.parseInt(br.readLine()));
        int p = 2;
        while(n >= 2){
            while(n % p == 0){
                System.out.print(p + "\t");
                n /= p;
            }
            p++;
        }
    }
}

Algorithm

Step 1: Input a positive number N.
Step 2: Let P = 2
Step 3: Repeat Step 4 through 7 while N >= 2:
Step 4: Repeat Step 5 through 6 while N is divisible by P:
Step 5: Display P
Step 6: N = N / P using Integer Division
Step 7: P = P + 1
Step 8: End

Leave a Reply