Project Euler: Problem 20

[This article was first published on We think therefore we 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.



n! means n x (n – 1) x … x 3 x 2 x 1
For example, 10! = 10 x 9 x … x 3 x 2 x 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 approach to this problem is quite similar to problem 16 which we can see here. We just need to deal with a really large number here. So, GMP again to the rescue.

library(gmp)

x <- factorialZ(100)

sum(as.numeric(unlist(strsplit(as.character(x), split=””))))
# as.character(x) coverts the big number into a string
# strsplit() extracts individual elements of the string. This can be ensured by using the split = “” argument, which splits the string one element at a time
# strsplit() returns a list. To access the elements of this list, use unlist()
# convert the individual characters to numeric using as.numeric()
# sum the elements

Ans: 648

To leave a comment for the author, please follow the link and comment on their blog: We think therefore we 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)