Reputation: 163
I am a python newbie. I am looking to compute (a ** b) % 10
in the most efficient way possible (i.e. simplifying the power part). I have found one way to do this: ((a % 10) ** b) % 10
. My question is, are there more efficient ways to do this? This problem is an extension of a CodeFights task. The original problem accepted (a ** b) % 10
.
Upvotes: 1
Views: 540
Reputation: 5421
Since the numbers mod 10 form a ring, you can compute the residue mod 10 at every intermediate value without influencing the result.
There is a O(log b)
step algorithm called Square-and-multiply that can drastically speed up your computations.
The basic idea is that for even b
, we can just square the argument
and divide the exponent by 2 without changing the result.
For odd b
, we extract one power of a
(or our current argument) and proceed like in the even case (squaring and halving).
So putting this together, if you implement the Square-and-multiply algorithm and compute the residue mod 10 after every step, you will have a nice and efficient way to compute your last digit.
Upvotes: 1
Reputation: 63
if n % 4 == 0:
x = 4
else:
x = n % 4
last_digit = (m ** x) % 10
Short Explanation: If you list out the initial expansions of a power, you will find a pattern. So we can reduce a and b to m and x respectively. Because it is just about the last digit.
you can visit: this site for the better explanation to find out last digit of a^b
Upvotes: 1