遍历到就可以结束了,如果此时数字还没有除数,则可判定其本身是一个质数,没有再除下去的必要了,直接打印其本身即可
string 转long
String str = sc.nextLine(); long num = Integer.valueOf(str).intValue();
import java.math.*;
long k = (long)Math.sqrt(num);
import java.util.*; import java.lang.*; import java.math.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); long num = Integer.valueOf(str).intValue(); long k = (long)Math.sqrt(num); for (long i = 2; i <= k; ++i) { while (num % i == 0) { System.out.print(i + " "); num /= i; } } System.out.println(num == 1 ? "": num+" "); } }