Prime factor and JavaScript

前端 未结 2 1102
刺人心
刺人心 2021-01-25 03:50

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 p

相关标签:
2条回答
  • 2021-01-25 04:24

    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>
    
    0 讨论(0)
  • 2021-01-25 04:25

    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.

    0 讨论(0)
提交回复
热议问题