These are my solutions in R to the first twenty-five problems defined by the Project Euler (named after Leonard Euler). This project is dedicated to computational problems intended to be solved with computer programs.
This solutions are all written in base R without the use of any libraries.
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 1,000.
This problem can be solved using either the modules function %%
or by generating a sequence and removing dumplicates.
# Determine modulus 3 and 5
answer <- sum((1:999)[((1:999)%%3 == 0) | ((1:999)%%5 == 0)])
# Alternative solution using sequences
answer <- sum(unique(c(seq(3, 999, 3), seq(5, 995, 5))))
The sum of all the multiples of 3 or 5 below 1,000 is 233,168.
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, \ldots\]
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Generate a sequence of Fibonacci numbers and sum all even numbers.
fib <- c(1, 2) #Define first two numbers
while (max(fib) < 4e+06) {
# Generate Fibonacci numbers until limit is reached
fib <- c(fib, fib[length(fib) - 1] + fib[length(fib)])
}
answer <- sum(fib[fib%%2 == 0])
The sum of even-valued terms of Fibonacci numbers not exceeding four million is 4,613,732.
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
The esieve
function defines all prime numbers from 1 to n using the Sieve of Eratosthenes. The prime.factors
function determines the prime factors by testing for all primes smaller than \(\lfloor \sqrt(n) \rfloor\) using the esieve
function.
# Sieve of Eratosthenes for generating primes 1:n
esieve <- function(n) {
if (n==1) return(NULL)
if (n==2) return(n)
# Create a list l of consecutive integers {2,3,…,N}.
# Exclude even numbers to save computing time
l <- c(2, seq(from=3, to=n, by=2))
# Start counter
i <- 1
# Select p as the first prime number in the list, p=2.
p <- 2
while (p^2<=n) {
# Remove all multiples of p from the l.
l <- l[l==p | l%%p!=0]
# set p equal to the next integer in l which has not been removed.
i <- i+1
# Repeat steps 3 and 4 until p2 > n, all the remaining numbers in the list are primes
p <- l[i]
}
return(l)
}
# Prime Factors
prime.factors <- function (n) {
factors <- c() # Define list of factors
primes <- esieve(floor(sqrt(n))) # Define primes to be tested
d <- which(n%%primes == 0) #
if (length(d) == 0) # Define candidate primes
return(n)
for (q in primes[d]) { # Test candidate primes
while (n%%q == 0) { # Generate list of factors
factors <- c(factors, q)
n <- n/q
}
}
if (n > 1) factors <- c(factors, n)
return(factors)
}
answer <- max(prime.factors(600851475143))
The largest prime factor of the number 600851475143 is 6857.
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is \(9009 = 91 \times 99\).
Find the largest palindrome made from the product of two 3-digit numbers.
This solution works backwards to fine the largest. Numbers are converted to character strings and reversed until a palindrome is found.
# Cycles through all number combinations, starting at 999
for (i in 999:900) {
for (j in 990:900) {
word <- as.character(i * j)
# Create reverse
reverse <- paste(rev(unlist(strsplit(word, ""))), collapse = "")
# Check whether palindrome
palindrome <- word == reverse
if (palindrome)
break
}
if (palindrome) {
break
}
}
answer <- i * j
The largest palindrome made from the product of two 3-digit numbers is 906,609.
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?
The solution will also be divisible by the number 1 to 10 so we can start at 2520 and increment by 2520. The loop checks for divisibility by the numbers 1 to 20.
# Start as high as possible
i <- 2520
# Check consequtive numbers for divisibility by 1:20
while (sum(i%%(1:20)) != 0) {
i <- i + 2520
}
answer <- i
The smallest positive number that is evenly divisible by all of the numbers from 1 to 20 is 232,792,560.
The sum of the squares of the first ten natural numbers is, \[1^2 + 2^2 + \ldots + 10^2 = 385\]
The square of the sum of the first ten natural numbers is,
\[(1 + 2 + \ldots + 10)^2 = 552 = 3025\]
The difference between the sum of the squares of the first ten natural numbers and the square of the sum is \(3025 - 385 = 2640\).
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
This is a straight forward problem for vector processing capabilities in R.
answer <- sum(1:100)^2 - sum((1:100)^2)
The difference between the sum of the squares of the first one hundred natural numbers and the square of the sum is 25,164,150.
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 1,0001st prime number?
is.prime <- function(n) {
primes <- esieve(ceiling(sqrt(n)))
prod(n%%primes != 0) == 1
}
i <- 2 # First Prime
n <- 1 # Start counter
while (n < 10001) {
# Find 10001 prime numbers
i <- i + 1 # Next number
if (is.prime(i)) {
# Test next number
n <- n + 1 # Increment counter
i <- i + 1 # Next prime is at least two away
}
}
answer <- i - 1
The 1,1000st prime is 104,743.
The four adjacent digits in the 1,000-digit number that have the greatest product are \(9 \times 9 \times 8 \times 9 = 5,832\).
Find the thirteen adjacent digits in the 1,000-digit number that have the greatest product. What is the value of this product?
Define digits as a character string and cycle through all 12-character ngrams to find the highest product.
# Define digits
digits <- "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
ngram <- 13 # Define length
answer <- 0
# Clycle through digits
for (i in 1:nchar(digits)) {
# Pick 13 consecutive digits
adjecent <- substr(digits, i, i + ngram - 1)
# Define product
mult <- prod(as.numeric(unlist(strsplit(adjecent, ""))))
# Largest?
if (mult > answer)
answer <- mult
}
The value of the product is 23,514,624,000.
A Pythagorean triplet is a set of three natural numbers, \(a < b < c\), for which,
\[a^2 + b^2 = c^2\]
For example, \(3^2 + 4^2 = 9 + 16 = 25 = 5^2\).
There exists exactly one Pythagorean triplet for which \(a + b + c = 1000\). Find the product \(abc\).
Brute force method using the fact that \(a < b < c\), and thus that \(a < s/3\), and \(a < b < s/2\) to optimise the search.
a <- 0
b <- 0
c <- 0
s <- 1000
found <- FALSE
for (a in 1:floor((s/3))) {
for (b in a:(s/2)) {
c <- s - a - b
if (a^2 + b^2 == c^2) {
found <- TRUE
break
}
}
if (found)
break
}
answer <- a * b * c
The product \(abc\) for the pythogarian triplet 200, 375, 425 is 31,875,000.
The sum of the primes below 10 is \(2 + 3 + 5 + 7 = 17\).
Find the sum of all the primes below two million.
Use the Sieve of Eratosthenes to find the primes and sum them.
answer <- sum(esieve(2 * 10^6))
The sum of all the primes below two million is 142,913,828,922.
What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the \(20 \times 20\) grid?
square <- readLines("p011_matrix.txt")
square <- as.numeric(unlist(lapply(square, function(x) {
strsplit(x, " ")
})))
square <- matrix(square, ncol = 20)
prod.vert <- square[1:17, ] * square[2:18, ] * square[3:19, ] * square[4:20, ]
prod.hori <- square[, 1:17] * square[, 2:18] * square[, 3:19] * square[, 4:20]
prod.dia1 <- square[1:17, 1:17] * square[2:18, 2:18] * square[3:19, 3:19] * square[4:20,
4:20]
prod.dia2 <- square[4:20, 1:17] * square[3:19, 2:18] * square[2:18, 3:19] * square[1:17,
4:20]
answer <- max(prod.vert, prod.hori, prod.dia1, prod.dia2)
the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the grid is 70,600,674
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be \(1 + 2 + 3 + 4 + 5 + 6 + 7 = 28\). The first ten terms would be:
\[1, 3, 6, 10, 15, 21, 28, 36, 45, 55, \ldots\]
Let us list the factors of the first seven triangle numbers:
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
# Determine number of factors
# http://mathschallenge.net/library/number/number_of_divisors Prime numbers
prime <- esieve(100)
nFactors <- function(x, prime = prime) {
m <- length(prime)
fac.count <- numeric(m)
for (i in 1:m) {
while (x%%prime[i] == 0) {
fac.count[i] <- fac.count[i] + 1
x = x/prime[i]
}
while (x == 1) break
}
return(prod(fac.count + 1))
}
# generate triangle numbers and count prime factors
i <- 1
divs <- 0
while (divs <= 500) {
triangle <- i * (i + 1)/2
divs <- nFactors(triangle, Primes(100))
i <- i + 1
}
answer <- triangle
The first triangle number with more than five hundred divisors is 76,576,500
Work out the first ten digits of the sum of one-hundred 50-digit numbers.
library(gmp) #Multiple Precision Arithmetic (big integers and rationals, prime number tests, matrix computation), 'arithmetic without limitations' using the C library GMP (GNU Multiple Precision Arithmetic).
numbers <- readLines("p013_numbers.txt")
answer <- as.bigz(sum(as.numeric(numbers)))
answer <- substr(as.character(answer), 1, 10)
The first ten digits of the sum of the nominated 50-digit numbers are 5537376230.
The following iterative sequence is defined for the set of positive integers:
\(n \rightarrow n/2\) (\(n\) is even)
\(n \rightarrow 3n + 1\) (\(n\) is odd)
Using the rule above and starting with 13, we generate the following sequence:
\[13 \rightarrow 40 \rightarrow 20 \rightarrow 10 \rightarrow 5 \rightarrow 16 \rightarrow 8 \rightarrow 4 \rightarrow 2 \rightarrow 1\]
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
# Define Collatz series
collatz <- function(n) {
chain <- vector()
i <- 1
while (n != 1) {
chain[i] <- n
i <- i + 1
if (n%%2 == 0)
n <- n/2 else n <- 3 * n + 1
}
return(c(chain, 1))
}
# Brute Force
solutions <- lapply(1:1e+06, function(x) length(collatz(x)))
answer <- which.max(unlist(solutions))
maxl <- max(unlist(solutions))
The starting number 837,799 produces the longest Collatz chain with 525 elements.
Starting in the top left corner of a \(2 \times 2\) grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a \(20 \times 20\) grid?
\(2^{15} = 32768\) and the sum of its digits is \(3 + 2 + 7 + 6 + 8 = 26\).
What is the sum of the digits of the number \(2^{1000}\)?
digits <- as.bigz(2^1000) # Define number
answer <- sum(as.numeric(unlist(strsplit(as.character(digits), ""))))
The sum of the digits of the number \(2^{1000}\) is 1366.
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are \(3 + 3 + 5 + 4 + 4 = 19\) letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of “and” when writing out numbers is in compliance with British usage.
# Vocabulary
single <- c("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
teens <- c("ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen")
tens <- c("ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty",
"ninety")
numwords <- c(single, teens)
# Create all number words from 1 to 1000
for (i in (length(numwords) + 1):999) {
numword <- ""
if (i >= 100) {
numword <- paste(single[floor(i/100)], "hundred")
if (i%%100 != 0)
numword <- paste(numword, "and")
}
remainder <- i - 100 * floor(i/100)
if (remainder != 0) {
if (remainder < 20) {
numword <- paste(numword, c(single, teens)[remainder])
} else {
numword <- paste(numword, tens[floor(remainder/10)])
numword <- paste(numword, single[remainder - 10 * floor(remainder/10)])
}
}
numwords <- c(numwords, numword)
}
numwords <- c(numwords, "one thousand")
# Total number of letters excluding spaces
answer <- sum(nchar(gsub(" ", "", numwords)))
The number of letter used to write all numbers from 1 to 1000 is 21,124.
By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
3 7 4 2 4 6 8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)
You are given the following information, but you may prefer to do some research for yourself.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
library(lubridate) # Functions to work with date-times and time-spans
dates <- seq.Date(as.Date("1901/1/1"), as.Date("2000/12/31"), "days")
answer <- sum(wday(dates[day(dates) == 1]) == 1)
In the 20th century, 171 first days of the month were on a Sunday.
\(n!\) means \(n \times (n - 1) \times \ldots \times 3 \times 2 \times 1\).
For example, \(10! = 10 \times 9 \times \ldots \times 3 \times 2 \times 1 = 3628800\), and the sum of the digits in the number \(10!\) is \(3 + 6 + 2 + 8 + 8 + 0 + 0 = 27\).
Find the sum of the digits in the number \(100!\)
digits <- factorialZ(100)
answer <- sum(as.numeric(unlist(strsplit(as.character(digits), ""))))
The sum of the digits in the number \(100!\) is 648.
Let \(d(n)\) be defined as the sum of proper divisors of \(n\) (numbers less than \(n\) which divide evenly into \(n\)).
If \(d(a) = b\) and \(d(b) = a\), where \(a \neq b\), then \(a\) and \(b\) are an amicable pair and each of \(a\) and \(b\) are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore \(d(220) = 284\). The proper divisors of 284 are 1, 2, 4, 71 and 142; so \(d(284) = 220\).
Evaluate the sum of all the amicable numbers under 10,000.
The proper
function defines all proper divisors for number \(x\). The loop tests all number from 2 to 10000 for amicability and concatenates the collection of amicable numbers. The last line removed duplicate entries.
proper <- function(x) {
(1:x)[x%%1:x == 0]
}
amicable.numbers <- vector()
for (i in 2:10000) {
ps <- sum(proper(i)) - i
amicable <- i == sum(proper(ps)) - ps & i != ps
if (amicable) {
amicable.numbers <- c(amicable.numbers, i, ps)
}
}
amicable.numbers <- unique(amicable.numbers)
The amicable numbers under 10,000 are: (220, 284), (1184, 1210), (2620, 2924), (5020, 5564), (6232, 6368). The sum of all amicable numbers under 10,000 is 31,626.
Using names.txt
, a 46KB text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth \(3 + 15 + 12 + 9 + 14 = 53\), is the 938th name in the list. So, COLIN would obtain a score of \(938 \times 53 = 49714\).
What is the total of all the name scores in the file?
# ETL: reads the file and converts it to an ordered vector.
names <- readLines("p022_names.txt", warn = F)
names <- unlist(strsplit(names, ","))
names <- gsub("[[:punct:]]", "", names)
names <- sort(names)
# Total Name scores
answer <- 0
code <- data.frame(row.names = LETTERS, NUM = 1:26)
for (i in names) {
value <- sum(code[unlist(strsplit(i, "")), "NUM"])
value <- value * which(names == i)
answer <- answer + value
}
The total of all the name scores in the file is 871,198,282.
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be \(1 + 2 + 4 + 7 + 14 = 28\), which means that 28 is a perfect number.
A number \(n\) is called deficient if the sum of its proper divisors is less than \(n\) and it is called abundant if this sum exceeds \(n\).
As 12 is the smallest abundant number, \(1 + 2 + 3 + 4 + 6 = 16\), the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28,123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
\[012 021 102 120 201 210\]
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
The Fibonacci sequence is defined by the recurrence relation: \(F_n = F_n-1 + F_n-2\), where \(F_1 = 1\) and \(F_2 = 1\)
Hence the first 12 terms will be:
\[F_1 = 1, F_2 = 1, F_3 = 2, F_4 = 3, F_5 = 5, F_6 = 8, F_7 = 13, F_8 = 21, F_9 = 34, F_{10} = 55, F_{11} = 89, F_{12} = 144\]
The 12th term, \(F_12\), is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
library(gmp)
fib <- 1 # First Fibonaci number
cur <- 1 # Current number in sequence
pre <- 1 # Previous number in sequence
index <- 2
while (nchar(as.character(fib)) < 1000) {
fib <- as.bigz(cur + pre) # Determine next Fibonacci number
pre <- cur
cur <- fib
index <- index + 1
}
The index of the first Fibionacci number with 1000 digits is 4782.
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
Where 0.1(6) means 0.166666, and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
nRecur <- function(n) {
x <- 1
remainders <- c(x)
repeat {
x <- (x * 10)%%n # remainder
if (x == 0)
{
return(0)
} # No fraction
if ((x %in% remainders))
{
break
} # When remainder duplicated. Break from loop.
remainders <- c(remainders, x) # Else add remainder to list.
}
return(length(remainders) - which(remainders == x) + 1) # Exclude non-repeating part of the decimal
}
answer <- which.max(sapply(1:1000, nRecur))
The numer 983 contains the longest recurring cycle in its decimal fraction.
Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
\[\begin{bmatrix} 21 & 22 & 23 & 24 & 25 \\ 20 & 7 & 8 & 9 & 10 \\ 19 & 6 & 1 & 2 & 11 \\ 18 & 5 & 4 & 3 & 12 \\ 17 & 16 & 15 & 14 & 13 \\ \end{bmatrix}\]It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
# Starting number
answer <- 1
# Define corners of subsequent matrices
for (n in seq(from = 3, to = 1001, by = 2)) {
corners <- seq(from = n * (n - 3) + 3, by = n - 1, length.out = 4)
answer <- answer + sum(corners)
}
The sum of the numbers on the diagonals in a 1001 by 1001 spiral is 669171001