我被用于解决问题的 JavaScript 代码所困扰,该代码指出:
13195 的质因数是 5、7、13 和 29。
数字 600851475143 的最大质因数是多少?
(这不是作业,是在线编码/数学挑战)
所以我想出了这个解决方案:
<html>
<head>
<script type="text/javascript">
// This function checks whether it's possible to divide the prime number
function al(n){
// k = 13195 is the number that I have to find the prime factor for
var k = 13195;
if (k%n) {
return;
}
else {
document.write(n + ' ');
}
}
</script>
</head>
<body>
<script type="text/javascript">
//a and b are just for counting from the number n to 2 to find the prime numbers
var a = 2;
for (var n = 13194 ; n>a ; n--) {
var b = 2;
//if the found number is divisible, we skip it
while(b<n) {
if (n % b == 0) {
break;
}
else if (b = n - 1){
al(n);
}
b++;
}
}
</script>
</body>
</html>
现在解决问题:输出这些数字:“2639 1885 1015 455 377 203 145 91 65 35 29 13 7 5”。这些不是素数。我查看了这些数字,发现数字 13195 除以 5(最后一个数字)得出第一个数字;第2639章13195 除以 7 得到 1885; ETC。
我究竟做错了什么?
您的问题不是数学问题 - 您只是在条件检查之一中存在错误。
Change if(b = n-1)
to if(b == n-1)
。现在,您的代码实际上并没有检查以确保某个因子是素数;而是进行了检查。相反,它分配的值n-1
to b
(对于奇数值n
)然后自动调用a1(b
),所以你的结果是所有可能的奇因数k
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)