Project Euler — problem 13

July 9, 2012
By

(This article was first published on Tony's bubble universe » R, and kindly contributed to R-bloggers)

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 his blog: Tony's bubble universe » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , ,

Comments are closed.