R solvements to Project Euler — problem 1
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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.
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.
- The sum of multiples of any given number a is easy to calculate with a*int(n/a)*(int(n/a)+1)/2.
- Firstly find those not multiples of 3 or 5, then subtract them from the sum of all.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.