0

I read such a algorithms to implement expmod computation in sicp

#+begin_src ipython :session sicp :results output
def expmod(base, exp, m):
    # base case
    if exp == 0: return 1
    if evenp(exp):
        return expmod(base, exp/2, m) ** 2 % m
    else:
        return base * expmod(base, exp-1, m) % m

def evenp(n):
    return n % 2 == 0

print(expmod(2, 8, 7))
 #+end_src

 #+RESULTS:
 : 4

The algorithms employed the principle that

 (x % mod) ** 2 = x**2 % mod

How could prove it?

Wizard
  • 103

1 Answers1

0

In general, this is wrong.

E.g.

$$(8\bmod 5)^2=9$$

but

$$(8^2)\bmod5=4.$$

  • 1
    One would presume that they meant they are congruent, in this case, 9%5 == 4%5. – Simply Beautiful Art Dec 18 '19 at 15:37
  • @SimplyBeautifulArt: sorry but I am answering the question as stated and as programmed. –  Dec 18 '19 at 15:38
  • 1
    The code provided ends the even and odd return lines with % m, which as I said, means they are congruent. – Simply Beautiful Art Dec 18 '19 at 15:42
  • @SimplyBeautifulArt: you are giving the OP misleading information. The code uses the modulo operator, which returns a value. There is no test for congruency. –  Dec 18 '19 at 15:45
  • appreciate it very much for the kind help. Got the idea of the code. – Wizard Dec 18 '19 at 15:45
  • 1
    @YvesDaoust You misunderstand my point. If every line ends with % m, which as you say, returns a value, then it's not possible to end up with values larger than m. As is in your answer, you get $9$, which would become $4$ as programmed. – Simply Beautiful Art Dec 18 '19 at 15:49
  • @SimplyBeautifulArt: (x % mod) ** 2 = x**2 % mod –  Dec 18 '19 at 15:54
  • 1
    That is the stated principal which holds if you mod both sides, which the given program does in fact do. – Simply Beautiful Art Dec 18 '19 at 15:55