modulus



The easiest way is mod(974^169,28552) =>  13616.

This is not terribly efficient, because Maxima first calculates the
505-digit integral result, then takes the modulus.   But it is
efficient enough.  If you start doing, say, 2345^16900,  this takes a
noticeable amount of time, but still not bad if you just need a value
here or there.

But if you do need more efficiency, it is better to perform modular
arithmetic in the first place.  Here is how you would do that in
Maxima:

modulus: 28522$      /* Maxima gives a warning for non-prime moduli */
rat(974)^28522;         /* Maxima only performs modular arithmetic on
'rat' numbers. */

Note that Maxima uses a 'balanced' representation for modular numbers, so

     modulus: 5$ rat(2)^2 => -1

When the result is < 0, you can convert it to the one-sided
representation by adding modulus.

You can package this functionality as follows:

  modexpt(a,b,modulus):=
     block( [result],
       result: ratdisrep( rat(a)^b ),
       if result>=0 then result else result+modulus);