Java 中已给数字的第 k 个质因数
以下 Java 程序打印某个数字 n 的第 k 个质因数,其中给出了 k 和 n。
程序
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); } } }
输出
Enter a number : 216 Enter the k value : 3 2 2 2 3 3 3 3th prime factor of the given number is :2
广告