有一个费马素数检验。写了这么一个函数。但是,从 17 开始,我得到任何素数 - 不是素数。我发现关键是js将大数转换为无穷大,然后除以模我得到NaN,因为算法不起作用。我能以某种方式解决这个问题吗?
let checkingTheNumberForSimplicity = (number, amountTest = 100) => {
for (let i = 0; i < amountTest; ++i) {
let n = Math.round(Math.random() * (number - 2)) + 1;
if ((n ** (number - 1)) % number !== 1) {
console.log((n ** (number - 1)));
console.log(n, i, (n ** (number - 1)) % number);
return false;
}
}
return true;
};
console.log(2, checkingTheNumberForSimplicity(2));
console.log(20, checkingTheNumberForSimplicity(20));
console.log(7, checkingTheNumberForSimplicity(7));
console.log(419, checkingTheNumberForSimplicity(419));
console.log(1123, checkingTheNumberForSimplicity(1123));
中可以安全使用的最大整数
JavaScriptNumber.MAX_SAFE_INTEGER = 9007199254740991。但是如果你使用 ,你可以修正寻找素数的算法
Math.sqrt(n),因为 只要除数小于该数的根,就可以寻找除数,否则除数将进一步重复。