Prime factor and JavaScript

冷暖自知 提交于 2019-12-31 04:13:06

问题


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

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>

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.

What exactly am I doing wrong?


回答1:


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

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.




回答2:


My javascript solution-

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


来源:https://stackoverflow.com/questions/8229037/prime-factor-and-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!