# EULER PROBLEM 1
# 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 <- sum((1:999) [((1:999) %% 3==0) | ((1:999) %% 5==0)])
print(answer)
## [1] 233168
# EULER PROBLEM 2
# 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, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million,
# find the sum of the even-valued terms.
fib <- 1 # First Fibonaci number
cur <- 1 # Current number in sequence
pre <- 1 # Previous number in sequence
answer <- 0
while (fib<4000000) {
fib <- cur+pre
if (fib%%2==0) {answer <- answer+fib}
pre <- cur
cur <- fib
}
print(answer)
## [1] 4613732
# EULER PROBLEM 3
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
n <- 600851475143
library(numbers)
answer <- max(primeFactors(n))
print(answer)
## [1] 6857
# EULER PROBLEM 4
# 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.
for (i in 999:900) {
for (j in 990:900) {
word <- as.character(i*j)
palindrome <- word==paste(rev(unlist(strsplit(word, ""))), collapse="")
if (palindrome) break
}
if (palindrome) {
print(i*j)
break
}
}
## [1] 906609
# EULER PROBLEM 5
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
i <- 2520
while (i%%2!=0 | i%%3!=0 | i%%4!=0 | i%%5!=0 | i%%6 != 0 | i%%7 != 0 | i%%8 != 0 | i%%9 != 0 |
i%%10 != 0 | i%%11 != 0 | i%%12 != 0 | i%%13 != 0 |
i%%14 != 0 | i%%15 != 0 | i%%16 != 0 | i%%17 != 0 |
i%%18 != 0 | i%%19 != 0 | i%%20 != 0) {
i <- i+20
}
print(i)
## [1] 232792560