[R] Arbitrary Precision Numbers

From: Rory Winston <rory.winston_at_gmail.com>
Date: Fri, 04 Apr 2008 08:43:23 -0700 (PDT)


(If you're wondering, this is a Project Euler question :))

If I wanted to calculate the sum of the digits in the decimal representation of 2^1000, what would be a good way to go about that? I've tried the following methods:

# Calculate the sum of digits in the decimal representation of 2^n
# Only works for smaller values of n

bsum <- function(n) {

	s <- 0
	e <- floor(log10(2^n))
	for (i in seq(e,0,-1)) {
		s <- s + (((2^n) %/% 10^i) %% 10)


The above doesnt work, as I am using an integer modulus which has insufficient precision. so I tried to coerce R to produce a full-precision integer and sum the digits of that:

bsum2 <- function(n) {

	s <- 0
	strn <- formatC(2^n, format="fg")

This also doesnt seem to work. Is there another way I can do this in R? Cheers

View this message in context: http://www.nabble.com/Arbitrary-Precision-Numbers-tp16492549p16492549.html
Sent from the R help mailing list archive at Nabble.com.

R-help_at_r-project.org mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Fri 04 Apr 2008 - 16:55:30 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 10 Apr 2008 - 16:30:28 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive