I have a vector with approximately 1000 elements from roughly 1 to 10 and I want the product of all elements multiplied together modulo 10^6. I.e., I want something akin to
x <- as.integer(runif(1000, 1, 10))
prod(x) %% 1000000
However, since prod(x)
evaluates to Inf
, the above simply returns NaN
.
In my actual application (which isn't exactly minimal, so I won't put it here), I've done this with a for
loop, like
x <- as.integer(runif(1000, 1, 10))
for (i in 1:length(x)) {
if (i == 1) {
y <- x[i]
} else {
y <- y * x[i]
y <- y %% 1000000
}
}
y
Initially I simply wanted to ask for help coming up with a better solution than a for
loop, assuming I should be avoiding this in R. However, in writing this question I'm now equally puzzled by the fact that I can't seem to generate a working MWE for the for
loop. The above code returns 0
, yet it works fine when I remove as.integer()
. I've spent longer than I care to admit trying to figure out why this is so, but I'm stumped.
Two questions, then:
- Why doesn't the above MWE work? (And why does it work without
as.integer
?) - What's a good way to implement modular multiplication in R that avoids overflow issues? Ideally I'd be curious for a solution in base R, i.e. without something like the
gmp
package. I've tried withsapply
/lapply
, but to no avail so far.
I've found similar questions posed in terms of other languages, but I struggle to decode the answers phrased in these terms, I'm afraid.