Arjen Markus 19 november 2002. In reaction to a discussion in the Tclers' chat room:

A function that is used quite regularly in cryptographic applications is:

P(n,r,m) = n^r mod m

(n^r denotes n to the power r, all three parameters are positive integers)

This function does not exist as such within the expr command, but it is simple to create a procedure that evaluates this function efficiently.

The parameters for this function are usually large enough to make a direct calculation impossible. But the trick is to recognise that n^r can be written as n^(r/2)*n^(r/2) when r is even. If r is odd, then write it as:

n^r = n * (n^(r-1))

and then we have the first case back.

Furthermore, the modulo function is very well behaved:

(h * g) mod m = ( (h mod m) * (g mod m) ) mod m

Given these observations, here is a recursive proc that evaluates the above function in at most 2*log2(r) steps. This can probably be improved, but I am a bit lazy.

Note that in the last test cases the intermediate numbers would be much too big to deal with directly:

52131^53124 = Order(10^246334)

or, to put it in another way, a figure with a quarter million digits

rmax -- If you want to use this function in real-world applications you might be interested in the following optimized version which runs 20..50% faster, depending on the Tcl version. Interpretation is left as an exercise to the reader.