Project Euler — problem 20

[This article was first published on Tony's bubble universe » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

It’s been quite a while since my last post on Euler problems. Today a visitor post his solution to the second problem nicely, which encouraged me to keep solving these problems. Just for fun!

10! = 10 * 9 * … * 3 * 2 * 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!

The 20th problem is a big number problem. As it’s getting late, I’ll cut to the chase and use the gmp package to calculate this big-number multiplication. It is meant to make my life much easier. The solution is very straightforward: convert to ‘bigz’s, then calculate as usual.

?View Code RSPLUS

1
2
3
4
5
6
require(gmp)
num.lst <- as.bigz(1:100)
product <- prod(num.lst)
dec.num <- strsplit(as.character(product), split = "")
result <- sum(as.numeric(unlist(dec.num)))
cat("The result is:", result, "\n")

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

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.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)