题解 | #质数因子#

质数因子

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

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    // Write your code here
    while ((line = await readline())) {
        let num = Number(line);
        let res = [];

        for (let index = 2; index * index <= num; index++) {
            while (num % index === 0) {
                res.push(index);
                num /= index;
            }
        }
        if (num > 1) {
            res.push(num);
        }
        console.log(res.join(" ").trim());
    }
})();

实现思路和短除法类似,从2开始算起一直除到不能被2整除为止,然后除3,一次进行除,能被4整除肯定能被2整除,能被9整除肯定能被3整除,当循环到4、6、9时被除数肯定不能被这几个数整除。为什么是index * index <= num,如果`index * index > num` 时`index` 肯定不能把`num` 出尽。

#23届找工作求助阵地##软件开发薪资爆料#
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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