题解 | #质数因子#
质数因子
http://www.nowcoder.com/practice/196534628ca6490ebce2e336b47b3607
这个问题大部分的解法都是这样,利用循环穷举。
Scanner scanner = new Scanner(System.in); long num = scanner.nextLong(); while(num != 1) { for (int i = 2; i <= num; ++i) { if (num % i == 0) { System.out.print(i + " "); num /= i; break; } } }
也不能说错,但是这个方法遇到大数就过不了。
所以要怎么优化呢?
1.降低循环次数,利用Math.sqrt
long k = (long) Math.sqrt(num);
2.利用双重循环,假如输入的数值能被2整除,那就一直整除下去
for (long i = 2; i <= k; ++i) { while (num % i == 0) { System.out.print(i + " "); num /= i; } }
3.最后再判断除完的数有没有大于1
System.out.println(num == 1 ? "": num+" ");
那么最终的解法是
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long num = scanner.nextLong(); 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+" "); } }