-6

As the title sais, i want to find the last digit of an 2^n number.

I know that it's about repetition of even numbers, but i don't know how to make it happen.

This is what I did:

return (2*ascii%10)%10 - 2;

But it's not the correct method

For example:

I got 2^97, find the last digit of this very large number. Thank you!

Mas
  • 11
  • 5

2 Answers2

3

Powers of 2:

2, 4, 8, 16, 32, 64, 128, 256...

Last digits:

2, 4, 8, 6, 2, 4, 8, 6...

Last digit of 2^i is:

int arr[4] = {2, 4, 8, 6};
return arr[(i-1)%4];
Benjy Kessler
  • 7,356
  • 6
  • 41
  • 69
  • Can you prove it's right? – luk32 Apr 22 '15 at 11:59
  • It's pretty self evident. The last digit of 2^i is only determined by the last digit of 2^(i-1). Once a cycle is encountered it will continue forever. – Benjy Kessler Apr 22 '15 at 12:00
  • Still not a strict proof. But at least a good hint. I mean currently the answer has no value, at least to me. If it was so obvious OP would not have any trouble figuring it out =). – luk32 Apr 22 '15 at 12:03
  • 3
    It's a simple induction proof. Try it :) – Benjy Kessler Apr 22 '15 at 12:04
  • I think you misunderstand. I know how to do it, but you are answering the question... I am just saying that giving away code with zero explanation has very little value, obviously OP couldn't do it. Though, at least the hint you gave was nice. I am not saying it's incorrect, just not very educational =) – luk32 Apr 22 '15 at 12:08
  • 1
    The OP is not asking for a demonstration, just a solution. I don't like this kind of questions but honestly he doesn't have to proof anything to anybody, is a right answer, period. – Jose Palma Apr 22 '15 at 12:17
0

Let's say that ld(x) means last digit of x. We got:

ld( pow( 2, 1 ) ) = 2

ld( pow( 2, 2 ) ) = 4

ld( pow( 2, 3 ) ) = 8

ld( pow( 2, 4 ) ) = 6

ld( pow( 2, 5 ) ) = 2

See a pattern here? There is one: if the exponent equals:

( multiple of 4 ) + 1 you got ld(x) == 2

( multiple of 4 ) + 2 you got ld(x) == 4

( multiple of 4 ) + 3 you got ld(x) == 8

( multiple of 4 ) + 0 you got ld(x) == 6

In C/C++ you can do it like that:

int lastDigit;
if ( exp == 0 )
    lastDigit = 1; // special case
int rem = exp % 4;
switch ( rem )
{
    case 1: lastDigit = 2;break;
    case 2: lastDigit = 4;break;
    case 3: lastDigit = 8;break;
    case 0: lastDigit = 6;break;
}
Lighthink
  • 704
  • 1
  • 7
  • 11
  • 1
    I think you meant exp == 0 in the special case. And you have to return afterwords. Also the switch has to be on rem+1 not rem. – Benjy Kessler Apr 22 '15 at 12:02
  • Yeah, it was exp == 0; thanks for pointing it out. As for rem + 1, I don't think that is correct. – Lighthink Apr 22 '15 at 12:03