k-th prime factor of a given number in java

Java Programming Java8Java.Util Package

Following is the Java program which prints the kth prime factor of a number n, when k and n are given.

Program

import java.util.Scanner;

public class KthPrimeFactor {
   public static void main(String args[]) {
      int number, k, factor = 0;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a number :");
     
      number = sc.nextInt();
      System.out.println("Enter the k value :");
      k = sc.nextInt();
      int temp = k-1;
     
      for(int i = 2; i< number; i++) {
         while(number%i == 0) {
            if(temp == 0) {
               factor = i;
            }
            temp--;
            System.out.println(i+" ");
            number = number/i;
         }
      }
      System.out.println(k+"th prime factor of the given number is :"+factor);
      if(number >2) {
         System.out.println(number);
      }
   }
}

Output

Enter a number :
216
Enter the k value :
3
2
2
2
3
3
3
3th prime factor of the given number is :2
raja
Published on 04-Jun-2018 13:24:02
Advertisements