主要因素和 JavaScript [英] Prime factor and JavaScript

查看:48
本文介绍了主要因素和 JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被我用来解决一个问题的 JavaScript 代码困住了:

I'm stuck with the JavaScript code I am using for solving a problem which states:

13195 的质因数是 5、7、13 和 29.600851475143 的最大质因数是多少?

The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?

(这不是家庭作业,是在线编码/数学挑战)

(this is not homework, is an online coding/mathematical challenge)

所以我想出了这个解决方案:

So I came up with this solution:

<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;等

Now to the problem: This outputs these numbers: "2639 1885 1015 455 377 203 145 91 65 35 29 13 7 5". These aren't prime numbers. I've looked at the numbers and I found that the number 13195 divided by 5 (the last number) gives the first number; 2639; 13195 divided by 7 gives 1885; etc.

我到底做错了什么?

推荐答案

您的问题不是数学问题 -- 您只是在条件检查中遇到了错误.

Your issue isn't a mathematical one -- you just have a bug in one of your conditional checks.

if(b = n-1)改为if(b == n-1).现在,您的代码实际上并未进行检查以确保因子是质数;相反,它将 n-1 的值分配给 b(对于 n 的奇数值),然后自动调用 a1(b),所以你的结果是 k 的所有可能的奇数因子.

Change if(b = n-1) to if(b == n-1). Right now, your code isn't actually checking to ensure that a factor is prime; instead, it's assigning the value of n-1 to b (for odd values of n) and then automatically calling a1(b), so your result is all possible odd factors of k.

这篇关于主要因素和 JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆