Project Euler Problem 1
February 10, 2015
Project Euler is a collection of math problems intended for computer solution, and is one of the inspirations for Programming Praxis. The first problem on Project Euler, which also regularly appears on lists of phone interview questions, asks you to:
Find the sum of all the multiples of 3 or 5 below 1000.
Your task is to write a program that solves Problem 1 for arbitrary n; since the problem is simple, you must provide at least three fundamentally different solutions. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Three ways…
(1) Brute force overall entries and summing them!
(2) Brute force summing muliples of 5, multiples of 3 and removing duplicate multiples of 15…
(3) Same as 2 but using formulae to compute sum – no need to brute force…
sub bf {
my $n = shift;
my $t = 0;
$t+= $_ foreach grep { !($_ % 3) || !($_ % 5) } 1..($n-1);
return $t;
}
sub x {
my $n = shift;
return _x($n,3)+_x($n,5)-_x($n,15);
}
sub _x {
my($n,$f)=@_;
my $s = 0;
my $t = 0;
while($t<$n) {
$s+=$t;
$t+=$f;
}
return $s;
}
sub yy {
my $n = shift;
return _y($n,3)+_y($n,5)-_y($n,15);
}
sub _y {
my($n,$f)=@_;
$n = int (($n-1)/$f);
return $f * ($n+1)*$n/2;
}
printf "%7d %20d %20d %20d\n", $_, bf($_), x($_), yy($_) foreach @ARGV;
My solution in Python.
Easy to extend, just add your own function as long as it starts with “solve_” and returns the result as an int.
Above code outputs for n = 1000:
Running method: solve_brute_force
233168
Run time (s): 0.0
Running method: solve_plain_math
233168
Run time (s): 0.0
Running method: solve_wheel_multiples
233168
Run time (s): 0.0
——————————————————–
For n = 10000000:
Running method: solve_brute_force
23333331666668
Run time (s): 1.47399997711
Running method: solve_plain_math
23333331666668
Run time (s): 0.0
Running method: solve_wheel_multiples
23333331666668
Run time (s): 0.986999988556
Similar solution using Gauss’s summation formula in SML:
Only two ways but they are more different. I suppose the sampling method
is O(sample size) space, while the gambling method is O(1) space, but the
sample size can be considered a constant. These count 0 as a multiple.