R solvements to Project Euler — problem 1

May 15, 2012
By

(This article was first published on Tony's bubble universe » R, and kindly contributed to R-bloggers)

Things have been going wild since I opened this blog. Tasks were piled up while I was tight on time. At present, I’m facing a major challenge in my life. However, I decide to spare some time for self-improvements.
R is one of the most useful tool I’ve learned in my research life. Learning R has been always in my to-do list but my practice is not enough. Thus, I’m starting a learning program, in which to solve problems in Project Euler would help me with R coding and mathematics thinking as well.
OK, enough talking. Let’s have a look at the very first problem of Euler’s.

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.

The idea is simple: firstly find the multiples of 3, and the multiples of 5, then sum them up. There is one issue though — the multiples of 3*5 would be added twice. So, they should be subtracted. The sum = (the sum of multiples of 3) + (the sum of multiples of 5) – (the sum of multiples of 15).
I’m gonna resolve this problem using these R function: %%, union, sum. I use union() here instead of subtraction of multiples of 15.

?View Code RSPLUS
1
2
3
4
5
6
7
num <- seq(1, 999)
multiples.3 <- num[num %% 3 == 0]
multiples.5 <- num[num %% 5 == 0]
num.request <- union(multiples.3, multiples.5)
result <- sum(num.request)
cat("The sum of all the multiples of 3 or 5 below 1000 is ", result, ".\n", 
    sep="")

I read the posts in Project Euler Forum, and two thoughts should be mentioned.

  1. The sum of multiples of any given number a is easy to calculate with a*int(n/a)*(int(n/a)+1)/2.
  2. Firstly find those not multiples of 3 or 5, then subtract them from the sum of all.

To leave a comment for the author, please follow the link and comment on his blog: Tony's bubble universe » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , ,

Comments are closed.