-
Notifications
You must be signed in to change notification settings - Fork 5
/
euler.php
executable file
·68 lines (63 loc) · 1.54 KB
/
euler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env php
<?php
# Problem #1:
# Answer: 233168
#
# 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.
#
function euler1() {
return array_sum(array_filter(range(3, 999),
create_function('$x',
'return ($x % 3 == 0) || ($x % 5 == 0);')));
}
# Problem #2:
# Answer: 4613732
#
# Each new term in the Fibonacci sequence is generated by adding the
# previous two terms. By starting with 1 and 2, the first 10 terms
# will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# Find the sum of all the even-valued terms in the sequence which do
# not exceed four million.
#
function euler2() {
$last1 = 2;
$last2 = 1;
$sum = 2;
while (1) {
$cur = $last1 + $last2;
if ($cur > 4000000) {
break;
}
if ($cur % 2 == 0) {
$sum += $cur;
}
$last2 = $last1;
$last1 = $cur;
}
return $sum;
}
$eulers = array(
1 => euler1,
2 => euler2,
);
if (isset($argc)) {
// Main
if ($argc == 1) {
// No command line args passed, so run them all.
foreach ($eulers as $num => $euler) {
echo "#" . $num . ". " . $euler() . "\n";
}
} else {
// Command line args passed, just run the requested ones.
foreach (array_slice($argv, 1) as $arg) {
echo "#" . $arg . ". " . eval('return euler' . $arg . '();') . "\n";
}
}
}
?>