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

No comments:

Post a Comment