素数因子和JavaScript

ahh*_*sad 1 javascript primes

我坚持使用我用来解决问题的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>
Run Code Online (Sandbox Code Playgroud)

现在问题:输出这些数字:"2639 1885 1015 455 377 203 145 91 65 35 29 13 7 5".这些不是素数.我查看了数字,我发现数字13195除以5(最后一个数字)给出第一个数字; 2639; 13195除以7得到1885; 等等

我究竟做错了什么?

Chr*_*s L 9

你的问题不是一个数学问题 - 你的一个条件检查中只有一个错误.

更改if(b = n-1)if(b == n-1).现在,你的代码实际上没有检查以确保一个因素是素数; 相反,它是分配的值n-1b(为奇数值n),然后自动调用a1(b),那么你的结果是所有可能的奇因素k.

  • @ahhsad Nope,没有使用特殊的分析工具,只是第二双眼睛.有时这就是你所需要的:) (8认同)