Search code examples
c++modulardigit

Second digit from the right from a huge number


Now I actually read about modular arithmetic and managed to get the last digit of some number. Okay. But now... How do I get second last digit? Second one on the right. I actually been working on it on several hours straight trying to find a simple solution, this is the best I could come up so far but it's still not it. Could somebody help me please?

This is what I have so far

long long powmod(long long n, long long exp)
{
    long long r, result = 1;

    while(exp)
    {
        r = exp % 2;
        exp /= 2;
        if(r == 1) result = result * n % 10;
        n = (n * n) % 10;
    }
    return result;
}

Thanks in advance


Solution

  • As you only asked for the second last digit, how about getting the last two digits, then dividing by ten?

    Ie, solve for a^n mod 100, then look at the tens digit.