Project Euler — problem 13

[This article was first published on Tony's bubble universe » 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.

The 13th in Project Euler is one big number problem:

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.

Obviously, there are some limits in machine representation of numbers. In R, 2^(-1074) is the smallest non-zero positive number, and 2^1023 is the largest. The numbers in the 13th problem is definitely within this range. Although, there is one global parameter to be modified. By default, if one sum up these 100 numbers naively, the result would be 5.537376e+13. This is due to the number of digits to print is 7 by default. Thus, to get the first 10 digits, you need to adjust this parameter a little bit.

?View Code RSPLUS
1
2
3
4
5
options(digits = 10)  
digits <- digits <- scan("clipboard", what = 0)
result <- sum(digits)
# the digits before e is the answer
# only nine digits will show, as the tenth number is zero

Two more things to be addressed.

  • R package gmp() is a specific package for big number calculation.
  • The first 10 digits in the sum is mostly dependent on the first 10 digits of 100 numbers. You could simply calculate the sum of these 100 first-10-digits (for safety reason, take first-11-digits) to get the result. Be ware of the option(digits) still to be changed.

To leave a comment for the author, please follow the link and comment on their blog: Tony's bubble universe » 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.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)