[Solved] Last digit of 2^n [closed]


If you look at the sequence of powers of two, you will se a pattern:

1
2
4
8
16
32
64
128
256
512
1024
2048

its always 2 -> 4 -> 8 -> 6

You can use this, to calculate the last digit

int GetLastDigit(int power)
{
    if (power == 0) return 1;
    switch ((power - 1) % 4)
    {
        case 0: return 2;
        case 1: return 4; 
        case 2: return 8; 
        case 3: return 6;
        default: return -1; //negative power.
    } 
}

BigInteger version:

static int GetLastDigit(BigInteger power)
{
    if (power == 0) return 1;
    switch ((int)((power - 1) % 4)) //you can cast it, because it will always be less than 4
    {
        case 0: return 2;
        case 1: return 4;
        case 2: return 8;
        case 3: return 6;
        default: return -1; //negative power. 
    }
}

17

solved Last digit of 2^n [closed]