Project Euler — problem 20

September 23, 2012
By

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

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 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.