在 JavaScript 中找到一个数的最大质因数
我们需要编写一个JavaScript函数,它接受一个数字作为唯一的参数。
作为参数提供的数字保证是合数(具有两个以上因数的数字)。我们的函数应该找到能精确整除输入数的最大素数。
例如-
如果参数是72,那么输出应该是3。
因为3是能整除72的最大素数
示例
以下是代码-
const num = 72;
const largestPrimeFactor = (num) => {
let res = Math.ceil(Math.sqrt(num));
const isPrime = (num) => {
let i, limit = Math.ceil(Math.sqrt(num));
for (i = 3; i <= limit; i += 2) {
if (num % i === 0) {
return false;
};
};
return true;
};
res = (res & 1) === 0 ? res - 1 : res;
while (!(num % res === 0 && isPrime(res))) {
res -= 2;
};
return res;
}
console.log(largestPrimeFactor(num));输出结果以下是控制台上的输出-
3
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短