Site icon R-bloggers

Project Euler: Problem 16

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

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?

Handling large numbers or rather, very large numbers, can be a pain at times. But have no fear, for GMP is here.

GMP  makes the solution quite simple.

library(gmp)

x <- as.bigz(2^1000)
# as.bigz() is a function in the gmp library that helps dealing with large numbers quite easily 

This is the approach we take
  1. Convert the number to a string so that we can extract the individual elements of the number
  2. Extract the individual elements or digits
  3. Create a vector of these digits
  4. Sum the vector
  5. Rejoice

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: 1366

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.