Thursday 15 March 2012

Project Euler: Problem 16


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

1 comment:

  1. I am very enjoyed for this blog. Its an informative topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy. I think it may be help all of you. Thanks. how many pints of blood is in the human body Thank you for this blog. That's all I can say. You most definitely have made this blog into something thats eye opening and important. You clearly know so much about the subject, you've covered so many bases. Great stuff from this part of the internet. Again, thank you for this blog.

    ReplyDelete