-1

// the following code is generating accurate answer in my editor, but I want to optimize the code to pass the tests in freecodecamp environment. Can anybody shed the light upon this problem?

            function isPrime(param) {
                if (param == 2) {
                    return true;
                }
                if (param % 2 == 0) {
                    return false;
                }
                var max = Math.ceil(Math.sqrt(param));
                for (var i = 3; i <= max; i += 2) {
                    if (param % i == 0) {
                        return false;
                    }
                }
                return true;
            }


            function primeSummation(n) {
                var primeArr = [];
                for (var i = 2; i < n; i++) {
                    if (isPrime(i)) {
                        primeArr.push(i);
                    }
                }
                var sumArray = primeArr.reduce(function add(a, b) {
                    return a + b;
                }, 0);
                console.log(sumArray)
                return sumArray;
            }

            primeSummation(2000000);
Will Ness
  • 62,652
  • 8
  • 86
  • 167
  • You can check this [link](https://stackoverflow.com/questions/40200089/javascript-number-prime-test) to find if number is prime or not & also normal `for` will be better than `reduce` – brk Feb 25 '19 at 09:53
  • Welcome to StackOverflow. It's great that you've joined bootcamp. There's a lot to learn, I keep my fingers crossed. If you're looking for best algorithm, that counts primes, this question has already been answered on StackOverflow: https://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking-if-a-number-is-prime – greenmarker Feb 25 '19 at 10:18
  • I would give primeArr to the isPrime function, at the moment you check for prime against every single odd number <= sqrt(candidate) when you can check against the primes <= sqrt(candidate number) this should cut drastically on the number of tests sqrt(2e6)=1414 and there's only about 220 primes but 700 odd numbers that 3.5 times more ! Also in prime summation you can add 2 as a prime and skip even numbers the same way you did it in isPrime. – Eponyme Web Feb 25 '19 at 10:37

1 Answers1

0

When you have a long range of natural numbers (1...n) to check for them being prime, then it is not efficient to test them individually like you do with isPrime. It will be more efficient to perform the sieve of Eratosthenes over that range and then calculate the sum from the resulting array.

trincot
  • 211,288
  • 25
  • 175
  • 211