Correctness, Invariants & Design
![Question 63, GATE 2015: DOSOMETHING(c,a,n) receives a bit array c[0..k−1] and positive integers a,n. It sets z=1; then for i=0,...,k−1 sets z=z² mod n, and, if c[i]=1, sets z=(z×a) mod n; finally it returns z. For k=4, c=(1,0,1,1), a=2, n=8, what is returned?](../../assets/questions/CS-2015-S3-Q63-1.webp)
Answer & solution
Official answer: 0
1. Iteration details: bit 1 gives 1²·2 mod 8=2; bit 0 gives 2² mod 8=4; bit 1 gives (4² mod 8)·2 mod 8=0; the last bit 1 keeps the value 0. Each iteration squares before the optional multiplication.
2. The loop processes the binary exponent 1011 from most significant bit to least. The successive z values modulo 8 are 2, 4, 0, 0: square and multiply by 2 when the current bit is 1. Equivalently it computes 211 mod8=0.