## Wrong results with "mod"

### Matthew Durkin (view profile)

on 10 Feb 2019
Latest activity Answered by John D'Errico

### John D'Errico (view profile)

on 10 Feb 2019
Why does Matlab give me the wrong answer to mod(14^27,55) = 32, it should equal 9. What am I doing wrong?

Matthew Durkin

### Matthew Durkin (view profile)

on 10 Feb 2019
Never mind, I found out I need to use "powermod" to get the answer.
the cyclist

### the cyclist (view profile)

on 10 Feb 2019
Maybe you should copy your comment to an answer, and accept it.

### John D'Errico (view profile)

on 10 Feb 2019

This fails because MATLAB cannot represent an integer larger than 2^53-1 as an exact integer, when working in double precision.
14^27 is far larger than that of course. So it fails. This leaves you with two basic options, to use symbolic arithmetic, (or perhaps my VPI toolbox) or to use powermod.
mod(sym(14)^27,55)
ans =
9
powermod(14,27,55)
ans =
9
The powermod solution is better of course, in the sense that the huge number 14^27 never had to be fully computed.