I first heard of Project Euler about a week ago on a Twitter thread I’ve since lost. It excited me enough to get started! I wish I knew about it earlier because the way these are set up provides ample opportunity to develop good computing intuition. I plan to do one of these a week. I’ll be posting my code with explanations on this blog for the first 100 problems (those are the only problems allowed to be distributed like that).
Before I explain the code for problem 1, I will drop it with the included comments here for your perusal:
# Solving Project Euler Problem 1
# Problem asks to find sum of all integer multiples of 3 and 5 below 1000
# Create integer sequences starting at 0 to increment correctly
a <- seq.int(0, 1000, by = 3)
b <- seq.int(0, 999, by = 5)
# Append vector b onto vector a for calculation
c <- append(a, b, length(a))
# Find the non-overlapping results
d <- unique(c)
# Find answer
sum(d)
The Problem
The problem set asks you to find the sum of all the integers (whole numbers) below 1,000 that are multiples of 3 or 5. There are many ways to approach it. This is a problem that can be solved by hand, though I chose to use code.
The Method
I chose to create two vectors by sequential separation using the seq.int() function which takes the argument form (lower-bound, upper-bound, increment). This returns only whole numbers (integers) between those bounds through skip-counting. I used the whole range to find multiples of 3. However, since the question excludes the number 1,000 and 1,000 is a multiple of 5, I had to shorten the range to 999 when finding multiples of 5.
This method created two vectors with partial answers. Unfortunately, some numbers are multiples of both 3 and 5 (15, 30, 60, etc) which means they show up in both vectors. The way I removed the duplicates was by using the append() function. I appended the second vector onto the first, starting after the end of the first vector (a, b, length(a)) and created a new vector to store this result. This vector contains duplicates. To remove the duplicates, I used the unique() function to create another vector with only non-duplicated answers. I then summed the resulting vector, which provided the answer, which you can find after running the code yourself. 😉