0

Okay so I have an assignment to compute the binary representation of an integer and then reverse it into right to left notation and place that into a vector and perform modular exponentiation on it. I have the binary representation down, but I get the wrong answer when it comes down to the modular exponentiation portion. It may be something stupid I missed in the code but I've looked at examples and can't seem to figure out what the problem may be. Here is the code for the modular exponentiation here.

int ModularExpo(int a, vector<int> K, int n) {
    if (n == 1) {
        return 0;
    }
    int b = 1;
    int A = a;
    if (K[0] == 1) {
        b = a;
    }
    for (unsigned int i = 1; i < K.size() - 1; i++) {
        A = A * A % n;
        if (K[i] == 1) {
            b = A * b % n;
        }
    }
    return b;
}

So basically I send in the base (a), the exponent in binary form as a vector reversed (K) and the modulus (n). Initialize 2 variables b and A then check the first index to see if the K is even or odd, then go into my loop summing up everything. Still can't figure it out.

Any help is appreciated, thanks.

kbman99
  • 21
  • 2

1 Answers1

0

Okay I actually figured it out. I wasn't looping all the way through the vector because I was using

i < K.size() - 1

when I should have used either

i < K.size()

or

i <= K.size() - 1

in my for loop.

kbman99
  • 21
  • 2
  • go with `i < K.size()` less behind-the-scenes math, assuming the compiler doesn't recognize the `-1` and `<=` and strip it back down to `i < K.size()`. – user4581301 Jul 05 '16 at 20:33