Euler Problem 16 – Power digit sum

Power digit sum

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?

I don’t know why this has been kept here after such a difficult problem 15. I mean this is simple especially with R. R never had any problem dealing with big numbers. The question is simple need to sum the digits of 2^1000.

I have written a one-line solution 😛

sum(as.numeric(unlist(strsplit(as.character(2^1000), ""))))
#[1] 1366

Here, I calculate 2 raise to 1000 th power, convert it into character, split each character separately, convert them into number and then sum them and boom – THE ANSWER!

Ok, the only tricky part is you need to run

options(scipen = 999)

before running the one-liner. This ensures that 2 ^ 1000 which is a 32 digit long number is represented as it is in complete number if this command is not run it will represent this number in scientific notation which would be something like 1.071509e+301 and then when you convert it into character and sum it , it would return NA’s.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s