TITLE: Where is the mathematical logic with this exponent behaviour?
QUESTION [6 upvotes]: I'm learning how the diffie-hellman key exchange algorithm, works and I came to a mathematical conflict which I can't understand its logic .
This is the story: ( yuu can bypass this , it's just a brief)
Alice and Bob wants to generate the same secret number for they can use to encrypt data. (Eve is the bad guy and listening to every transmission over the network).
Alice                       Eve                    Bob

secret 15                                          secret 13    

Alice says to Bob ( let's choose the formula : `3^e % 17`)

                         Eve knows now 3,7


3^secret % 17 =6
3^15 % 17 = 6             ---->                    6    
                       Eve knows now 3,7,6
                                                 3^secret % 17 = 12  
                                                 3^13 % 17 = 12
12                          <----       
                       Eve knows now 3,7,6,12



(bob's 12)^secret %17
12^15 %17 = 10                      


                                                  (Alice's 6)^secret %17 
                                                  6^13 %17 = 10

They got the same number 10  , and it's hard for Eve to try figure 10 with very large numbers
And it's becuase :




(3^13 % 17) ^ 15 %17        is equal to         ((3^15 % 17)^13 %17)

But I was wondering about that : 
(3^13 % 17) ^ 15 %17

It appears that (3^13 % 17) ^ 15 %17 is equal also to (3^13 ) ^ 15 %17
My question is what is the logic behind it. I'm not asking for the accurate mathematical proof , I just want to understand the simple-human-logic behind this.

REPLY [2 votes]: Assuming the number and base are positive, all the modulo operator n % 17 does is to give you the last "digit" of $n$ when written in base 17.
Now when you want to calculate the last digit (base 17) of $(n^{13})^{15}$, you could calculate $x=n^{13}$, then raise $x$ to the power $15$, then look at the last digit. In order to raise your big number $x$ to the power $15$, you have to multiply a bunch of numbers (all equal to $x$) together. But if all you care about is the last digit (base 17) of the answer, all you need to know is the last digit of $x$, because when you do a multiplication longhand only the digits in the last column affect the last column of the answer. This is perhaps easier to convince yourself of working in base 10, since that's how we're used to doing long multiplication, but it works equally well in any base -- the last digit of $a\times b$ only depends on the last digits of $a$ and $b$.