-
Notifications
You must be signed in to change notification settings - Fork 5
/
euler.R
38 lines (34 loc) · 873 Bytes
/
euler.R
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
# 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.
xs <- 1:999
euler1 <- sum(xs[xs %% 3 == 0 | xs %% 5 == 0])
# Problem #2
# Answer:
#
# 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.
e2fib <- function(n) {
fibs <- c(length=n)
fibs[1] <- 1
fibs[2] <- 2
for (i in 3:n) {
fibs[i] <- fibs[i - 1] + fibs[i - 2]
if (fibs[i] > n) {
break
}
}
fibs
}
xs <- e2fib(4E6)
euler2 <- sum(xs[xs %% 2 == 0])