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.
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
- Convert the number to a string so that we can extract the individual elements of the number
- Extract the individual elements or digits
- Create a vector of these digits
- Sum the vector
# 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