in SPOJ

SPOJ: 3442. The last digit

Nestor was doing the work of his math class about three days but he is tired of make operations a lot and he should deliver his task tomorrow. His math’s teacher gives two numbers a and b. The problem consist in find the last digit of the potency of base a and index b. Help Nestor with his problem. You are given two integer numbers: the base a (0 <= a <= 20) and the index b (0 <= b <= 2,147,483,000). You have to find the last digit of a^b.

Problem: Sphere Online Judge (SPOJ) – Problem LASTDIG

Solution: I don’t really have an background in number theory, so I decided to approach this problem empirically. My main source of information was this small Python program:

for i in xrange(1, 20):
    print i, str(base ** i)[-1:]

I checked the last digit for each base (0..20) and looked for patterns. Happily, I found them. Here’s a snippet:

x > 0

0 ^ x => 1
1 ^ x => 1
2 ^ x => 2^1 -> 2
         2^2 -> 4
         2^3 -> 8
         2^4 -> 6

3 ^ x => 3^1 -> 3
         3^2 -> 9
         3^3 -> 7
         3^4 -> 1

4 ^ x => 4^1 -> 4
         4^2 -> 6

5 ^ x => 5

The rest is straight forward and thanks to the 700B source code size limitations, the source code is pretty unreadable. ;)

Write a Comment

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.