COLCOIN - Collecting Coins - algorithm

I am solving this problem - COLCOIN - Collecting Coins on spoj.
link- https://www.spoj.com/problems/COLCOIN/
where for a given set of denominations, and money you want, the bank gives you the coins with highest denominations, until it can't anymore and then move to the next highest denomination. ex: if the denominations are [1,2,3,4,8], if you request 23 rupees, it gives you two 8 rupee coins first and as it can't give any more 8 rupee coins, moves to next denomination and gives you one 4 rupee and one 3 rupee.
The problem is to find the maximum of number of distinct denominations you can get given an input of denominations. money you request from bank is a variable, it actually shouldn't come into the picture if I am correct.
this is my idea:
try to sum up the value of lower denominations and see if they can add up to a bigger denominations,and if they are you'll never get all the smaller denominations.
ex: let's say there is 1, 2 and 5. 1+2< 5. so you can get all denominations. for 8 = 5+2+1
another: let's say there are denominations 3,4 and 5. so 3+4>5 so, we can never get all the denominations. because money will be given in denominations of 5 until the money that should be given is less than 5. and obviously you can't get 3+4= 7 rupees for something less than 5
One other idea which obviously is wrong is to start with 2nd highest denomination and find the coins which we will add upto that and return that solution+1(highest denomination).
it is not correct because, for example, [1,2,4,17,19], if we count 19 already in try to sum up others for 18, we get 1+17, only 2 denominations other than, where as 26 would have given 4 denominations 19+4+2+1

I think you can use the following approach:
Start with the lowest denomination
Check if adding the next lowest denomination exceeds the denomination after that
If the sum is smaller, add the denomination to the sum
otherwise continue and check if the denomination one step further doesn't exceed the denomination after that.
Example: 1 3 6 8 15 20
different denominations d = 1, sum = 1
1 + 3 < 6: d = 2, sum = 4
4 + 6 >= 8: d = 2, sum = 4
4 + 8 < 15: d = 3, sum = 12
12 + 15 >= 20: d = 3, sum = 12
12 + 20 < infinity: d = 4, sum = 32
=> answer is 4 (and the amount to withdraw is 32).
Implementation:
// expects the denominations to be ordered from smallest to largest
// and also expects them to be unique
function findMaxDenominationsInSingleWithdrawal(denominations) {
if (denominations.length <= 2)
return denominations.length
let sum = denominations[0], d = 1
for (let index = 1; index + 1 < denominations.length; index++) {
if (sum + denominations[index] < denominations[index + 1]) {
d++
sum += denominations[index]
}
}
return d + 1
}
console.log(findMaxDenominationsInSingleWithdrawal([1, 3, 6, 8, 15, 20]))

Related

Finding the maximum possible sum/product combination of integers

Given an input of a list of N integers always starting with 1, for example: 1, 4, 2, 3, 5. And some target integer T.
Processing the list in order, the algorithm decides whether to add or multiply the number by the current score to achieve the maximum possible output < T.
For example: [input] 1, 4, 2, 3, 5 T=40
1 + 4 = 5
5 * 2 = 10
10 * 3 = 30
30 + 5 = 35 which is < 40, so valid.
But
1 * 4 = 4
4 * 2 = 8
8 * 3 = 24
24 * 5 = 120 which is > 40, so invalid.
I'm having trouble conceptualizing this in an algorithm -- I'm just looking for advice on how to think about it or at most pseudo-code. How would I go about coding this?
My first instinct was to think about the +/* as 1/0, and then test permutations like 0000 (where length == N-1, I think), then 0001, then 0011, then 0111, then 1111, then 1000, etc. etc.
But I don't know how to put that into pseudo-code given a general N integers. Any help would be appreciated.
You can use recursive to implement the permutations. Python code below:
MINIMUM = -2147483648
def solve(input, T, index, temp):
# if negative value exists in input, remove below two lines
if temp >= T:
return MINIMUM
if index == len(input):
return temp
ans0 = solve(input, T, index + 1, temp + input[index])
ans1 = solve(input, T, index + 1, temp * input[index])
return max(ans0, ans1)
print(solve([1, 4, 2, 3, 5], 40, 1, 1))
But this method requires O(2^n) time complexity.

Split sequence of numbers from 1 to n^2 in n subsequences so they all have the same sum

Given the number n and a sequence of numbers from 1 to n^2 how to split it in n subsequences so all of the subsequences have the same sum and length of n ?
For example if n = 3 answer could be:
3 4 8 = 15
2 6 7 = 15
1 5 9 = 15
So I feel this problem can be solved by making few observations to the problem.
For example, let's say we have n=3. Then n^2=9.
Now total sum of all the numbers from 1 to 9 = 9 * (9+1) / 2 = 45.
So, now we can split 45 into three equal groups each having sum = 45/3 = 5.
Similarly:-
n = 4, sum of 1 to 16 numbers = 16 * 17/2 = 136. each group sum = 136/4 = 34.
n = 5, sum of 1 to 25 numbers = 25 * 26/2 = 25*13. each group sum = 25*13/5 = 65.
Now, we know what should be sum of each set of groups in order to split numbers into n sub sequences.
Now Another observation that we make is whether our n is odd or even.
For n being even, the splitting it very easy.
n = 2, so we have numbers 1 to 4.
1 4
2 3.
Let's assume a matrix of n x n , in above case it will be 2 x 2.
Rules for even n:-
1. Keep a counter = 1.
2. Fill the first column (1 to n), incrementing the counter by 1.
3. When we reach at the bottom of the column, for column 2, we do a reverse iteration (n to 1) and fill them with counter by incrementing it by 1.
You can verify this technique will work by taking n=2,4,6 ... and filling the array.
Now let's see how to fill this matrix n x n for n odd.
Rules for odd n:-
1. Keep a counter = 1.
2. Fill the first column (1 to n), incrementing the counter by 1.
3. Now this case is slightly different from even case, from the next column onwards,
we don't reverse our calculation from n to 1 but we keep moving ahead in column.
Let's understand this step by looking at an example.
Let's take n=3.
Our first column will be 1,2,3.
Now for the second column we start at bottom column which is n in our example it's 3.
Fill the n = 3 with value 4. next row value = (n+1)%n = 0, which gets 5, next row = (n+1+1)%n = 1 , which gets value 6. Now all the column 2 values are filled, let's move onto next column i.e third.
We will start at row = 1 , so row 1 column 3 will get 7, then row 2 column 3 will get 8 and then row 0 column 3 will get 9.
Hope this helps!

Divide n into x random parts

What I need to achieve is basically x dice rolls = n sum but backwards.
So let's create an example:
The dice has to be rolled 5 times (min. sum 5, max. sum 30) which means:
x = 5
Let's say in this case the sum that was rolled is 23 which means:
n = 23
So what I need is to get the any of the possible single dice roll combinations (e.g. 6, 4, 5, 3, 5)
What I could make up in my mind so far is:
Create 5 random numbers.
Add them up and get the sum.
Now divide every single random number by the sum and multiply by the wanted number 23.
The result is 5 random numbers that equal the wanted number 23.
The problem is that this one returns random values (decimals, values below 1 and above 6) depending on the random numbers. I can not find a way to edit the formula to only return integers >= 1 or <= 6.
If you don't need to scale it up by far the easiest way is to re-randomize it until you get the right sum. It takes milliseconds on any modern cpu. Not pretty tho.
#!/usr/local/bin/lua
math.randomseed(os.time())
function divs(n,x)
local a = {}
repeat
local s = 0
for i=1,x do
a[i] = math.random(6)
s = s + a[i]
end
until s==n
return a
end
a = divs(23,5)
for k,v in pairs(a) do print(k,v) end
This was an interesting problem. Here's my take:
EDIT: I missed the fact that you needed them to be dice rolls. Here's a new take. As a bonus, you can specify the number of sides of the dices in an optional parameter.
local function getDiceRolls(n, num_rolls, num_sides)
num_sides = num_sides or 6
assert(n >= num_rolls, "n must be greater than num_rolls")
assert(n <= num_rolls * num_sides, "n is too big for the number of dices and sides")
local rolls = {}
for i=1, num_rolls do rolls[i] = 1 end
for i=num_rolls+1, n do
local index = math.random(1,num_rolls)
while rolls[index] == num_sides do
index = (index % num_rolls) + 1
end
rolls[index] = rolls[index] + 1
end
return rolls
end
-- tests:
print(unpack(getDiceRolls(21, 4))) -- 6 4 6 5
print(unpack(getDiceRolls(21, 4))) -- 5 5 6 5
print(unpack(getDiceRolls(13, 3))) -- 4 3 6
print(unpack(getDiceRolls(13, 3))) -- 5 5 3
print(unpack(getDiceRolls(30, 3, 20))) -- 9 10 11
print(unpack(getDiceRolls(7, 7))) -- 1 1 1 1 1 1 1
print(unpack(getDiceRolls(7, 8))) -- error
print(unpack(getDiceRolls(13, 2))) -- error
If the # of rolls does not change wildly, but the sum does, then it would be worth creating a lookup table for combinations of a given sum. You would generate every combination, and for each one compute the sum, then add the combination to a list associated to that sum. The lookup table would look like this:
T = {12 = {{1,2,3,4,2},{2,5,3,1,1},{2,2,2,3,3}, ...}, 13=....}
Then when you want to randomly select a combo for n=23, you look in table for key 23, the list has all combos with that sum, now just randomly pick one of them. Same for any other number.

Project Euler - 68

I have already read What is an "external node" of a "magic" 3-gon ring? and I have solved problems up until 90 but this n-gon thing totally baffles me as I don't understand the question at all.
So I take this ring and I understand that the external circles are 4, 5, 6 as they are outside the inner circle. Now he says there are eight solutions. And the eight solutions are without much explanation listed below. Let me take
9 4,2,3; 5,3,1; 6,1,2
9 4,3,2; 6,2,1; 5,1,3
So how do we arrive at the 2 solutions? I understand 4, 3, 2, is in straight line and 6,2,1 is in straight line and 5, 1, 3 are in a straight line and they are in clockwise so the second solution makes sense.
Questions
Why does the first solution 4,2,3; 5,3,1; 6,1,2 go anti clock wise? Should it not be 423 612 and then 531?
How do we arrive at 8 solutions. Is it just randomly picking three numbers? What exactly does it mean to solve a "N-gon"?
The first doesn't go anti-clockwise. It's what you get from the configuration
4
\
2
/ \
1---3---5
/
6
when you go clockwise, starting with the smallest number in the outer ring.
How do we arrive at 8 solutions. Is it just randomly picking three numbers? What exactly does it mean to solve a "N-gon"?
For an N-gon, you have an inner N-gon, and for each side of the N-gon one spike, like
X
|
X---X---X
| |
X---X---X
|
X
so that the spike together with the side of the inner N-gon connects a group of three places. A "solution" of the N-gon is a configuration where you placed the numbers from 1 to 2*N so that each of the N groups sums to the same value.
The places at the end of the spikes appear in only one group each, the places on the vertices of the inner N-gon in two. So the sum of the sums of all groups is
N
∑ k + ∑{ numbers on vertices }
k=1
The sum of the numbers on the vertices of the inner N-gon is at least 1 + 2 + ... + N = N*(N+1)/2 and at most (N+1) + (N+2) + ... + 2*N = N² + N*(N+1)/2 = N*(3*N+1)/2.
Hence the sum of the sums of all groups is between
N*(2*N+1) + N*(N+1)/2 = N*(5*N+3)/2
and
N*(2*N+1) + N*(3*N+1)/2 = N*(7*N+3)/2
inclusive, and the sum per group must be between
(5*N+3)/2
and
(7*N+3)/2
again inclusive.
For the triangle - N = 3 - the bounds are (5*3+3)/2 = 9 and (7*3+3)/2 = 12. For a square - N = 4 - the bounds are (5*4+3)/2 = 11.5 and (7*4+3)/2 = 15.5 - since the sum must be an integer, the possible sums are 12, 13, 14, 15.
Going back to the triangle, if the sum of each group is 9, the sum of the sums is 27, and the sum of the numbers on the vertices must be 27 - (1+2+3+4+5+6) = 27 - 21 = 6 = 1+2+3, so the numbers on the vertices are 1, 2 and 3.
For the sum to be 9, the value at the end of the spike for the side connecting 1 and 2 must be 6, for the side connecting 1 and 3, the spike value must be 5, and 4 for the side connecting 2 and 3.
If you start with the smallest value on the spikes - 4 - you know you have to place 2 and 3 on the vertices of the side that spike protrudes from. There are two ways to arrange the two numbers there, leading to the two solutions for sum 9.
If the sum of each group is 10, the sum of the sums is 30, and the sum of the numbers on the vertices must be 9. To represent 9 as the sum of three distinct numbers from 1 to 6, you have the possibilities
1 + 2 + 6
1 + 3 + 5
2 + 3 + 4
For the first group, you have one side connecting 1 and 2, so you'd need a 7 on the end of the spike to make 10 - no solution.
For the third group, the minimal sum of two of the numbers is 5, but 5+6 = 11 > 10, so there's no place for the 6 - no solution.
For the second group, the sums of the sides are
1 + 3 = 4 -- 6 on the spike
1 + 5 = 6 -- 4 on the spike
3 + 5 = 8 -- 2 on the spike
and you have two ways to arrange 3 and 5, so that the group is either 2-3-5 or 2-5-3, the rest follows again.
The solutions for the sums 11 and 12 can be obtained similarly, or by replacing k with 7-k in the solutions for the sums 9 resp. 10.
To solve the problem, you must now find out
what it means to obtain a 16-digit string or a 17-digit string
which sum for the groups gives rise to the largest value when the numbers are concatenated in the prescribed way.
(And use pencil and paper for the fastest solution.)

How to find the units digit of a certain power in a simplest way

How to find out the units digit of a certain number (e.g. 3 power 2011). What logic should I use to find the answer to this problem?
For base 3:
3^1 = 3
3^2 = 9
3^3 = 27
3^4 = 81
3^5 = 243
3^6 = 729
3^7 = 2187
...
That is the units digit has only 4 possibilities and then it repeats in ever the same cycle.
With the help of Euler's theorem we can show that this holds for any integer n, meaning their units digit will repeat after at most 4 consecutive exponents. Looking only at the units digit of an arbitrary product is equivalent to taking the remainder of the multiplication modulo 10, for example:
2^7 % 10 = 128 % 10 = 8
It can also be shown (and is quite intuitive) that for an arbitrary base, the units digit of any power will only depend on the units digit of the base itself - that is 2013^2013 has the same units digit as 3^2013.
We can exploit both facts to come up with an extremely fast algorithm (thanks for the help - with kind permission I may present a much faster version).
The idea is this: As we know that for any number 0-9 there will be at most 4 different outcomes, we can as well store them in a lookup table:
{ 0,0,0,0, 1,1,1,1, 6,2,4,8, 1,3,9,7, 6,4,6,4,
5,5,5,5, 6,6,6,6, 1,7,9,3, 6,8,4,2, 1,9,1,9 }
That's the possible outcomes for 0-9 in that order, grouped in fours. The idea is now for an exponentiation n^a to
first take the base mod 10 => := i
go to index 4*i in our table (it's the starting offset of that particular digit)
take the exponent mod 4 => := off (as stated by Euler's theorem we only have four possible outcomes!)
add off to 4*i to get the result
Now to make this as efficient as possible, some tweaks are applied to the basic arithmetic operations:
Multiplying by 4 is equivalent to shifting two to the left ('<< 2')
Taking a number a % 4 is equivalent to saying a&3 (masking the 1 and 2 bit, which form the remainder % 4)
The algorithm in C:
static int table[] = {
0, 0, 0, 0, 1, 1, 1, 1, 6, 2, 4, 8, 1, 3, 9, 7, 6, 4, 6, 4,
5, 5, 5, 5, 6, 6, 6, 6, 1, 7, 9, 3, 6, 8, 4, 2, 1, 9, 1, 9
};
int /* assume n>=0, a>0 */
unit_digit(int n, int a)
{
return table[((n%10)<<2)+(a&3)];
}
Proof for the initial claims
From observing we noticed that the units digit for 3^x repeats every fourth power. The claim was that this holds for any integer. But how is this actually proven? As it turns out that it's quite easy using modular arithmetic. If we are only interested in the units digit, we can perform our calculations modulo 10. It's equivalent to say the units digit cycles after 4 exponents or to say
a^4 congruent 1 mod 10
If this holds, then for example
a^5 mod 10 = a^4 * a^1 mod 10 = a^4 mod 10 * a^1 mod 10 = a^1 mod 10
that is, a^5 yields the same units digit as a^1 and so on.
From Euler's theorem we know that
a^phi(10) mod 10 = 1 mod 10
where phi(10) is the numbers between 1 and 10 that are co-prime to 10 (i.e. their gcd is equal to 1). The numbers < 10 co-prime to 10 are 1,3,7 and 9. So phi(10) = 4 and this proves that really a^4 mod 10 = 1 mod 10.
The last claim to prove is that for exponentiations where the base is >= 10 it suffices to just look at the base's units digit. Lets say our base is x >= 10, so we can say that x = x_0 + 10*x_1 + 100*x_2 + ... (base 10 representation)
Using modular representation it's easy to see that indeed
x ^ y mod 10
= (x_0 + 10*x_1 + 100*x_2 + ...) ^ y mod 10
= x_0^y + a_1 * (10*x_1)^y-1 + a_2 * (100*x_2)^y-2 + ... + a_n * (10^n) mod 10
= x_0^y mod 10
where a_i are coefficients that include powers of x_0 but finally not relevant since the whole product a_i * (10 * x_i)^y-i will be divisible by 10.
You should look at Modular exponentiation. What you want is the same of calculating n^e (mod m) with m = 10. That is the same thing as calculating the remainder of the division by ten of n^e.
You are probably interested in the Right-to-left binary method to calculate it, since it's the most time-efficient one and the easiest not too hard to implement. Here is the pseudocode, from Wikipedia:
function modular_pow(base, exponent, modulus)
result := 1
while exponent > 0
if (exponent & 1) equals 1:
result = (result * base) mod modulus
exponent := exponent >> 1
base = (base * base) mod modulus
return result
After that, just call it with modulus = 10 for you desired base and exponent and there's your answer.
EDIT: for an even simpler method, less efficient CPU-wise but more memory-wise, check out the Memory-efficient section of the article on Wikipedia. The logic is straightforward enough:
function modular_pow(base, exponent, modulus)
c := 1
for e_prime = 1 to exponent
c := (c * base) mod modulus
return c
I'm sure there's a proper mathematical way to solve this, but I would suggest that since you only care about the last digit and since in theory every number multiplied by itself repeatedly should generate a repeating pattern eventually (when looking only at the last digit), you could simply perform the multiplications until you detect the first repetition and then map your exponent into the appropriate position in the pattern that you built.
Note that because you only care about the last digit, you can further simplify things by truncating your input number down to its ones-digit before you start building your pattern mapping. This will let you to determine the last digit even for arbitrarily large inputs that would otherwise cause an overflow on the first or second multiplication.
Here's a basic example in JavaScript: http://jsfiddle.net/dtyuA/2/
function lastDigit(base, exponent) {
if (exponent < 0) {
alert("stupid user, negative values are not supported");
return 0;
}
if (exponent == 0) {
return 1;
}
var baseString = base + '';
var lastBaseDigit = baseString.substring(baseString.length - 1);
var lastDigit = lastBaseDigit;
var pattern = [];
do {
pattern.push(lastDigit);
var nextProduct = (lastDigit * lastBaseDigit) + '';
lastDigit = nextProduct.substring(nextProduct.length - 1);
} while (lastDigit != lastBaseDigit);
return pattern[(exponent - 1) % pattern.length];
};
function doMath() {
var base = parseInt(document.getElementById("base").value, 10);
var exp = parseInt(document.getElementById("exp").value, 10);
console.log(lastDigit(base, exp));
};
console.log(lastDigit(3003, 5));
Base: <input id="base" type="text" value="3" /> <br>
Exponent: <input id="exp" type="text" value="2011"><br>
<input type="button" value="Submit" onclick="doMath();" />
And the last digit in 3^2011 is 7, by the way.
We can start by inspecting the last digit of each result obtained by raising the base 10 digits to successive powers:
d d^2 d^3 d^4 d^5 d^6 d^7 d^8 d^9 (mod 10)
--- --- --- --- --- --- --- --- ---
0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1
2 4 8 6 2 4 8 6 2
3 9 7 1 3 9 7 1 3
4 6 4 6 4 6 4 6 4
5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6
7 9 3 1 7 9 3 1 7
8 4 2 6 8 4 2 6 8
9 1 9 1 9 1 9 1 9
We can see that in all cases the last digit cycles through no more than four distinct values. Using this fact, and assuming that n is a non-negative integer and p is a positive integer, we can compute the result fairly directly (e.g. in Javascript):
function lastDigit(n, p) {
var d = n % 10;
return [d, (d*d)%10, (d*d*d)%10, (d*d*d*d)%10][(p-1) % 4];
}
... or even more simply:
function lastDigit(n, p) {
return Math.pow(n % 10, (p-1) % 4 + 1) % 10;
}
lastDigit(3, 2011)
/* 7 */
The second function is equivalent to the first. Note that even though it uses exponentiation, it never works with a number larger than nine to the fourth power (6561).
The key to solving this type of question lies in Euler's theorem.
This theorem allows us to say that a^phi(m) mod m = 1 mod m, if and only if a and m are coprime. That is, a and m do not divide evenly. If this is the case, (and for your example it is), we can solve the problem on paper, without any programming what so ever.
Let's solve for the unit digit of 3^2011, as in your example. This is equivalent to 3^2011 mod 10.
The first step is to check is 3 and 10 are co-prime. They do not divide evenly, so we can use Euler's theorem.
We also need to compute what the totient, or phi value, is for 10. For 10, it is 4. For 100 phi is 40, 1000 is 4000, etc.
Using Euler's theorem, we can see that 3^4 mod 10 = 1. We can then re-write the original example as:
3^2011 mod 10 = 3^(4*502 + 3) mod 10 = 3^(4*502) mod 10 + 3^3 mod 10 = 1^502 * 3^3 mod 10 = 27 mod 10 = 7
Thus, the last digit of 3^2011 is 7.
As you saw, this required no programming whatsoever and I solved this example on a piece of scratch paper.
You ppl are making simple thing complicated.
Suppose u want to find out the unit digit of abc ^ xyz .
divide the power xyz by 4,if remainder is 1 ans is c^1=c.
if xyz%4=2 ans is unit digit of c^2.
else if xyz%4=3 ans is unit digit of c^3.
if xyz%4=0
then we need to check whether c is 5,then ans is 5
if c is even ans is 6
if c is odd (other than 5 ) ans is 1.
Bellow is a table with the power and the unit digit of 3 to that power.
0 1
1 3
2 9
3 7
4 1
5 3
6 9
7 7
Using this table you can see that the unit digit can be 1, 3, 9, 7 and the sequence repeats in this order for higher powers of 3. Using this logic you can find that the unit digit of (3 power 2011) is 7. You can use the same algorithm for the general case.
Here's a trick that works for numbers that aren't a multiple of a factor of the base (for base 10, it can't be a multiple of 2 or 5.) Let's use base 3. What you're trying to find is 3^2011 mod 10. Find powers of 3, starting with 3^1, until you find one with the last digit 1. For 3, you get 3^4=81. Write the original power as (3^4)^502*3^3. Using modular arithmetic, (3^4)^502*3^3 is congruent to (has the same last digit as) 1^502*3^3. So 3^2011 and 3^3 have the same last digit, which is 7.
Here's some pseudocode to explain it in general. This finds the last digit of b^n in base B.
// Find the smallest power of b ending in 1.
i=1
while ((b^i % B) != 1) {
i++
}
// b^i has the last digit 1
a=n % i
// For some value of j, b^n == (b^i)^j * b^a, which is congruent to b^a
return b^a % B
You'd need to be careful to prevent an infinite loop, if no power of b ends in 1 (in base 10, multiples of 2 or 5 don't work.)
Find out the repeating set in this case, it is 3,9,7,1 and it repeats in the same order for ever....so divide 2011 by 4 which will give you a reminder 3. That is the 3rd element in the repeating set. This is the easiest way to find for any given no. say if asked for 3^31, then the reminder of 31/4 is 3 and so 7 is the unit digit. for 3^9, 9/4 is 1 and so the unit will be 3. 3^100, the unit will be 1.
If you have the number and exponent separate it's easy.
Let n1 is the number and n2 is the power. And ** represents power.
assume n1>0.
% means modulo division.
pseudo code will look like this
def last_digit(n1, n2)
if n2==0 then return 1 end
last = n1%10
mod = (n2%4).zero? ? 4 : (n2%4)
last_digit = (last**mod)%10
end
Explanation:
We need to consider only the last digit of the number because that determines the last digit of the power.
it's the maths property that count of possibility of each digits(0-9) power's last digit is at most 4.
1) Now if the exponent is zero we know the last digit would be 1.
2) Get the last digit by %10 on the number(n1)
3) %4 on the exponent(n2)- if the output is zero we have to consider that as 4 because n2 can't be zero. if %4 is non zero we have to consider %4 value.
4) now we have at most 9**4. This is easy for the computer to calculate.
take the %10 on that number. You have the last digit.

Resources