1

I have a javascript algorithm which prints out the prime factors of a number based on a user's input.

    <script>
    var number = parseInt( prompt("Enter the number";""))
    var divisor = 2;
    while( number >= divisor){
        if (number % divisor == 0) {
            document.write(divisor + "");
        } else {
            divisor++;
        }
    }
    </script>

This code runs in (N-1) times at its worst, and I need to make it run ((N/2)/2) + 1 times. For example, if I test input number 53, it will take 14 loops instead of 52. How do I make it more efficient?

htr
  • 19
  • 1
  • 2
    you only need to check up to `Math.sqrt(number)` – d9ngle May 19 '17 at 12:32
  • 1
    Your assumption is incorrect, e.g. for 1,000,001 you need to check upto 1001 (because 1001 is the first number with x*x > 1,000,001). Note that 1001 is a lot smaller than N/4+1. Also, you can skip all even numbers higher than 2, and you need to actually divide by the divisor, otherwise you'll never get a good result for e.g. 8 = 2*2*2. – Peter B May 19 '17 at 12:35
  • Your if else us wrong.it will only print one prime number and run forever – Jonas Wilms May 19 '17 at 12:35

0 Answers0