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.
Answer
1
233168
C
1 2 3 4 5 6 7 8 9 10 11 12 13
#include<stdio.h>
intmain(int argc, char **argv) { int sum = 0; for (int i = 0; i < 1000; i++) { if (i % 3 == 0 || i % 5 == 0) { sum += i; } } printf("%d\n", sum); return0; }
Java
1 2 3 4 5 6 7
// This forces every solution class to implement a common interface, // which is helpful for unit testing like in the EulerTest implementation. publicinterfaceEulerSolution{ public String run(); }
publicfinalclassp001implementsEulerSolution{ publicstaticvoidmain(String[] args){ System.out.println(new p001().run()); } /* * Computers are fast, so we can implement this solution directly without any clever math. * A conservative upper bound for the sum is 1000 * 1000, which fits in a Java int type. */ public String run(){ int sum = 0; for (int i = 0; i < 1000; i++) { if (i % 3 == 0 || i % 5 == 0) sum += i; } return Integer.toString(sum); } }