题解 | #质数因子#

质数因子

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);
        // 注意 hasNext 和 hasNextLine 的区别
        long temp = in.nextLong();
        StringBuffer returnString = new StringBuffer("");
        long k = (long)Math.sqrt(temp);
        for(long i=2L;i <= k;i++){
            if(temp % i == 0){
                while(temp % i==0 && temp > 0){
                    returnString.append(i);
                    returnString.append(" ");
                    // 能除尽2 则一直除2 
                    // 能除尽3 则一直除3
                    // 4 已经不存在
                    // 能除尽5 则一直除5
                    // .......
                    // 直到不能被除尽 则最后不能被除尽的值如果不是1
                    // 则它也是质因子
                    temp = temp/i;
                }
            }
        }
        if(temp != 1){
            returnString.append(temp);
        }
        System.out.println(returnString);
    }
}

全部评论
取 i <= sqrt(temp) 因为最大的质因子 可能为 sqrt(x) 也可能 为 最后一个不能被除尽的 temp 。而对于 i 不需要 大于 sqrt(temp)的值 因为 若有 x*y == temp 则 x 与 y 要么等大 即 x==y==sqrt(temp) 要么 x和y一个大一个小
点赞 回复 分享
发布于 2024-04-05 14:39 河北

相关推荐

牛客96763241...:杭电✌️也是打完招呼,没人回吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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