I wrote a recursive modular exponentiation using the squared function, which works correctly but generates warnings:
msquare <- function(x,n) (x*x) %% n
mod.exp <- function(a,k,n){
ifelse(k <= 2,
a^k %% n,
ifelse(k %% 2 == 0,
msquare(mod.exp(a,k %/% 2,n),n),
(a * msquare(mod.exp(a,k %/% 2,n),n)) %% n))
}
I wrote it using ifelse, so I could use it vectorized by indicators:
powers <- mod.exp(2,1:348,349)
When I run the above code, it triggers a lot of warnings, for example:
In ifelse (k <= 2, a ^ k %% n, ifelse (k %% 2 == 0, msquare (mod.exp (a, ...: probable total loss of accuracy modulo
( Python pow()), 100% . , 2*348^2 = 242208, , .
? , , , .
. , :
powers <- sapply(1:348, function(x) mod.exp(2,x,349))
, .