-
Notifications
You must be signed in to change notification settings - Fork 5
/
euler.fan
101 lines (96 loc) · 2.47 KB
/
euler.fan
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class Euler
{
/**
* Euler #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.
*/
static Int euler1() {
sum := 0
(3..<1000).each |n| {
if (n % 3 == 0 || n % 5 == 0) {
sum = sum + n
}
}
return sum
}
/**
* Euler #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.
*/
static Int euler2() {
n := 2
a := 1
b := 2
while (true) {
c := a + b;
if (4000000 <= c) {
break
}
if (0 == c % 2) {
n += c
}
a = b
b = c
}
return n
}
/**
* Problem #4
* Answer: 906609
*
* A palindromic number reads the same both ways. The largest
* palindrome made from the product of two 2-digit numbers is 9009 =
* 91 99.
*
* Find the largest palindrome made from the product of two 3-digit
* numbers.
*/
static Bool is_palindromic_number(Int n)
{
s := "$n"
return s == s.reverse()
}
static Int euler4()
{
result := 0
(100..<1000).each |i| {
(0..<1000).each |j| {
p := i * j
if (p > result && Euler.is_palindromic_number(p)) {
result = p
}
}
}
return result
}
static Void main(Str[] args) {
// Kinda lame that we need an instance just to use trap for
// dynamic invokes, but that appears to be the case....
euler := Euler.make()
if (args.size > 0) {
args.each |Str arg| {
v := euler.trap("euler$arg", [,])
echo("#$arg: $v")
}
} else {
// TODO: Some other more dynamic means of reflecting each method...
[1].each |index| {
v := euler.trap("euler$index", [,])
echo("#$index: $v")
}
}
}
}