Project Euler Problem #1 (v2)

Revision 2 of this benchmark created on


Description

Project Euler Problem #1

http://projecteuler.net/index.php?section=problems&id=1

states:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

We can:

  1. collect all multiples of 3 and 5 in a set, so that there are no duplicates, and sum all the elements of the set
  2. sum all the multiples of 3, then add all the multiples of 5, then subtract all the multiples of 15 (because the common multiples were summed twice)

What's the fastest solution?

Preparation HTML

<script>
  var a = 3,
      b = 5,
      n, max = 1000,
      sum = 0;
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Use object as set to avoid duplicates
var multiples = {};

n = a;
while (n < max) {
 multiples[n] = true;
 n += a;
}

n = b;
while (n < max) {
 multiples[n] = true;
 n += b;
}

for (n in multiples) {
 sum += Number(n);
}
ready
Add all multiples, then subtract multiples in common
var axb = a * b;

n = a;
while (n < max) {
 sum += n;
 n += a;
}

n = b;
while (n < max) {
 sum += n;
 n += b;
}

n = a * b;
while (n < max) {
 sum -= n;
 n += axb;
}
ready
Shorter
for (n=a;n<max;n++)
  if (n%a==0 || n%b==0)
    sum += n;
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.