Write a program to find all prime factors of a given number.

The program should print the factors of a number which are prime.

One way of writing this is

  1. If the number is divisible by 2, repeatedly divide the number by 2 until it is no longer divisible by 2.
  2. Print 2 as a factor if number is divisible.
  3. In a loop for values of i from 3 to n in steps of 2, find if a number is divisible by i.
  4. If yes repeatedly divide by i as long as number is divisible.
Here is the complete program
import java.util.Scanner; 
class PrimeFactors{
     void printFactors(int num){
          if(num%2==0){
            System.out.println("2 ");
            while (num%2==0)
             num = num/2;
          } 
          for(int i=3;i<=num;i+=2){
               if(num%i==0){
                    System.out.println(i);
                  while(num%i==0)
                     num = num/i;
               } 
          }

     }

     public static void main(String args[]){
         PrimeFactors pf = new PrimeFactors();
         int n;
         Scanner scanner = new Scanner(System.in);
         n  = scanner.nextInt();
         pf.printFactors(n);
     }
}