[R] Arbitrary Precision Numbers

Rory Winston rory.winston at gmail.com
Fri Apr 4 17:43:23 CEST 2008


Hi

(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)
	}
	s
}	

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")
	sum(as.numeric(strsplit(strn,"")[[1]]))
}

This also doesnt seem to work. Is there another way I can do this in R?
Cheers
Rory
-- 
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.



More information about the R-help mailing list