2

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

ImQ009
  • 325
  • 4
  • 12
  • 3
    If you know how to get the right hand digit, then given a number like 1234, what would you divide by to get 123, which you already know how to get the right hand digit of? – Greg Hewgill Nov 19 '12 at 21:17

2 Answers2

3

Divide it by ten, round down, and then get the last digit of what remains. :-)

mdoyle
  • 737
  • 9
  • 22
  • by "it", do you mean the result of `n^exp`, using ordinary non-modular exponentiation? That works as long as the result fits within a `long long`, but what if the OP wants the second digit of `2^1000`? – Kevin Nov 19 '12 at 21:22
  • Yes, this is where the problem is at, I know I could just divide it by ten but it wouln't really work for big numbers – ImQ009 Nov 19 '12 at 21:23
1

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.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524