[R] Arbitrary Precision Numbers
jim holtman
jholtman at gmail.com
Sat Apr 5 03:26:31 CEST 2008
One way of "doing it in R" is to use the 'bc' command that is on most
UNIX/LINUX systems and is also on cygwin for Windows. Here are
decimal digits for 2^1000
/cygdrive/c/jph/consulting/2008-03-30: bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
2^1000
10715086071862673209484250490600018105614048117055336074437503883703\
51051124936122493198378815695858127594672917553146825187145285692314\
04359845775746985748039345677748242309854210746050623711418779541821\
53046474983581941267398767559165543946077062914571196477686542167660\
429831652624386837205668069376
So you can 'shell' the command from R, collect the digits and then sum them.
On Fri, Apr 4, 2008 at 10:43 AM, Rory Winston <rory.winston at gmail.com> wrote:
>
> 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.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem you are trying to solve?
More information about the R-help
mailing list