素数因子和JavaScript

时间:2011-11-22 15:09:56

标签: 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>

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

我究竟做错了什么?

2 个答案:

答案 0 :(得分:9)

您的问题不是数学问题 - 您的某项条件检查中只有一个错误。

if(b = n-1)更改为if(b == n-1)。现在,你的代码实际上没有检查以确保一个因素是素数;相反,它将n-1的值分配给b(对于n的奇数值)然后自动调用a1(b),因此您的结果是所有可能的奇数因子{ {1}}。

答案 1 :(得分:1)

我的javascript解决方案 -

<script type="text/javascript">
function largestPrimeFactor(number) {
var i = 2;
while (i <= number) {
    if (number % i == 0) {
        number /= i;    
    } else {
        i++;
    }
}
console.log(i);
}
var a = 600851475143 ; 
largestPrimeFactor(a)
</script>