Problem 10 Euler Summation of Primes

This is my solution to the problem 10 of Project Euler in the Coding Interview Prep section of this great website!

For now, I am struggling with those tests in which it’s required to make large iterations; for example: for (let i = 0; i < 99999999999; i++). Doing this throws a message that could be: “Potential Infinite Loop” or “timeout”.
That happens when you click on the “Run the Tests” button.

I expect comments on this solution, and suggestions on dealing with large iterations:

function primeSummation(n) {
  const array = new Array(n-1).fill(1).map((y,i) => y = i+1);

// I created a new Array with a length of n-1, but since this is constructor, it creates an array containing empty slots. So, I used fill() to put a "1" in each of the empty slots. And with map(), I created an array going from 1 to "n-1" value passed to the function.

  return array.filter(v => array.filter(x => v % x ==0).length == 2).reduce((sum,x) => sum + x,0);;

// Lastly, I created this "filter inside filter". The first one offers the "v" value to the second one, for getting the remainder against all the elements in the array. Whe doing this, the inside filter returns arrays.length, and the outside filter returns those arrays whose length is equals to 2 (since a prime number is only divisible by one and by itself). Finally, with the reduce method a obtain the sum of the numbers required.



// Console.log for checking

Good work getting a working solution.

Oof, those allocations aren’t cheap and O(n^2) will hurt as n gets big.

I would look at a prime number sieve in this case. For a problem like this, it’s the easiest way to get all of the primes in a range on values.

Thank you for answering.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.