Loss of accuracy in module warning despite correct results

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))

, .

+4
1

- ifelse, .

. :

2^60 %% 349
[1] 210

2^61 %% 349
[1] 71
Warning message:
probable complete loss of accuracy in modulus 

msquare <- function(x,n) {
  message("msquare ", length(x))
  (x*x) %% n
}

mod.exp <- function(a,k,n) {
  print(k)
  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))
}

# let print the warning as it happens, without delay
powers <- withCallingHandlers(
  mod.exp(2, 1:62, 349), 
  warning = function(w) {
    print(w)
    invokeRestart("muffleWarning")
  }
)

, , if-branch ( ).

+2

Source: https://habr.com/ru/post/1693170/


All Articles