题解 | 质数因子

质数因子

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

const readline = require("readline");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});
let endLine: number;
let tar_number: number = 2;
let target: Array<Number> = [];
rl.on("line", function (line) {
    endLine = Number(line);
}).on("close", () => {
    // caculate(Number(endLine), tar_number);
    console.log(caculate(endLine).join(" "));
});
function caculate(hex: number):number[] {
    const factors:number[] = []
    // 处理2的因子
    while(hex%2==0){
        factors.push(2)
        hex = hex/2
    }
    // 处理基数的因子
    for(let index = 3;index<=Math.sqrt(hex);index+=2){
        while(hex%index==0){
            factors.push(index)
            hex = hex/index
        }
    }
    if(hex>2){
        factors.push(hex)
    }
    return factors
}
function primeFactors(n: number): number[] {
    const factors: number[] = [];

    // 处理2的因子
    while (n % 2 === 0) {
        factors.push(2);
        n = n / 2;
    }

    // 处理奇数因子
    for (let i = 3; i <= Math.sqrt(n); i += 2) {
        while (n % i === 0) {
            factors.push(i);
            n = n / i;
        }
    }

    // 如果剩余的n是大于2的质数
    if (n > 2) {
        factors.push(n);
    }

    return factors;
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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