注释详解 | #质数因子#

质数因子

https://www.nowcoder.com/practice/196534628ca6490ebce2e336b47b3607


import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            long num = in.nextLong();
            double sqrt = Math.sqrt(num);
//            一个数最多有一个质因数大于它的平方根。如果num没有被除完,那么剩余的数,一定是num的质因数。
            for (long i = 2; i <= sqrt; i++) {

//                // 判断是否为质数(正序遍历无需判断当前数是否为质数)
//                boolean flags = true;
//                for (int j = 2; j <= Math.sqrt(i); j++) {
//                    if (i % j == 0) {
//                        flags = false;
//                        break;
//                    }
//                }
//                if (flags) {

                // 持续除当前数直到不能被整除,然后再继续找下一个数
                while (num % i == 0) {
                    num = num / i;
                    System.out.print(i + " ");
                }
            }

//            如果当前数大于最初求质因数的数的平方根,那么当前数也是它的质因数
            if (num > sqrt) {
                System.out.println(num);
            }
        }
    }
}


全部评论

相关推荐

09-01 17:26
已编辑
门头沟学院
点赞 评论 收藏
分享
牛客21331815...:像我一投就pass,根本不用焦虑泡池子
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务