Divide n into x random parts - random

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.

Related

Advanced Algorithms Problems ("Nice Triangle"): Prime number Pyramid where every number depends on numbers above it

I'm currently studying for an advanced algorithms and datastructures exam, and I simply can't seem to solve one of the practice-problems which is the following:
1.14) "Nice Triangle"
A "nice" triangle is defined in the following way:
There are three different numbers which the triangle consists of, namely the first three prime numbers (2, 3 and 5).
Every number depends on the two numbers below it in the following way.
Numbers are the same, resulting number is also the same. (2, 2 => 2)
Numbers are different, resulting number is the remaining number. (2, 3 => 5)
Given an integer N with length L, corresponding to the base of the triangle, determine the last element at the top
For example:
Given N = 25555 (and thus L = 5), the triangle looks like this:
2
3 5
2 5 5
3 5 5 5
2 5 5 5 5
=> 2 is the result of this example
What does the fact that every number is prime have to do with the problem?
By using a naive approach (simply calculating every single row), one obtains a time-complexity of O(L^2).
However, the professor said, it's possible with O(L), but I simply can't find any pattern!!!
I'm not sure why this problem would be used in an advanced algorithms course, but yes, you can do this in O(l) = O(log n) time.
There are a couple ways you can do it, but they both rely on recognizing that:
For the problem statement, it doesn't matter what digits you use. Lets use 0, 1, and 2 instead of 2, 3, and 5. Then
If a and b are the input numbers and c is the output, then c = -(a+b) mod 3
You can build the whole triangle using c = a+b mod 3 instead, and then just negate every second row.
Now the two ways you can do this in O(log n) time are:
For each digit d in the input, calculate the number of times (call it k) that it gets added into the final sum, add up all the kd mod 3, and then negate the result if you started with an even number of digits. That takes constant time per digit. Alternatively:
recognize that you can do arithmetic on n-sized values in constant time. Make a value that is a bit mask of all the digits in n. That takes 2 bits each. Then by using bitwise operations you can calculate each row from the previous one in constant time, for O(log n) time altogether.
Here's an implementation of the 2nd way in python:
def niceTriangle(n):
# a vector of 3-bit integers mod 3
rowvec = 0
# a vector of 1 for each number in the row
onevec = 0
# number of rows remaining
rows = 0
# mapping for digits 0-9
digitmap = [0, 0, 0, 1, 1, 2, 2, 2, 2, 2]
# first convert n into the first row
while n > 0:
digit = digitmap[n % 10]
n = n//10
rows += 1
onevec = (onevec << 3) + 1
rowvec = (rowvec << 3) + digit
if rows%2 == 0:
# we have an even number of rows -- negate everything
rowvec = ((rowvec&onevec)<<1) | ((rowvec>>1)&onevec)
while rows > 1:
# add each number to its neighbor
rowvec += (rowvec >> 3)
# isolate the entries >= 3, by adding 1 to each number and
# getting the 2^2 bit
gt3 = ((rowvec + onevec) >> 2) & onevec
# subtract 3 from all the greater entries
rowvec -= gt3*3
rows -= 1
return [2,3,5][rowvec%4]

Number of ways to change coins in constant time?

Let's say I have three types of coins -- a penny (0.01), a nickel (0.05), and a dime (0.10) and I want to find the number of ways to make change of a certain amount. For example to change 27 cents:
change(amount=27, coins=[1,5,10])
One of the more common ways to approach this problem is recursively/dynamically: to find the number of ways to make that change without a particular coin, and then deduct that coin amount and find the ways to do it with that coin.
But, I'm wondering if there is a way to do it using a cached value and mod operator. For example:
10 cents can be changed 4 ways:
10 pennies
1 dime
2 nickels
1 nickel, 5 pennies
5 cents can be changed 2 ways:
1 nickel
5 pennies
1-4 cents can be changed 1 way:
1-4 pennies
For example, this is wrong, but my idea was along the lines of:
def change(amount, coins=[1,5,10]):
cache = {10: 4, 5: 2, 1: 1}
for coin in sorted(coins, reverse=True):
# yes this will give zerodivision
# and a penny shouldn't be multiplied
# but this is just to demonstrate the basic idea
ways = (amount % coin) * cache[coin]
amount = amount % ways
return ways
If so, how would that algorithm work? Any language (or pseudo-language) is fine.
Precomputing the number of change possibilities for 10 cents and 5 cents cannot be applied to bigger values in a straight forward way, but for special cases like the given example of pennies, nickels and dimes a formula for the number of change possibilities can be derived when looking into more detail how the different ways of change for 5 and 10 cents can be combined.
Lets first look at multiples of 10. Having e.g. n=20 cents, the first 10 cents can be changed in 4 ways, so can the second group of 10 cents. That would make 4x4 = 16 ways of change. But not all combinations are different: a dime for the first 10 cents and 10 pennies for the other 10 cents is the same as having 10 pennies for the first 10 cents and a dime for the second 10 cents. So we have to count the possibilities in an ordered way: that would give (n/10+3) choose 3 possibilities. But still not all possibilities in this counting are different: choosing a nickel and 5 pennies for the first and the second group of 10 cents gives the same change as choosing two nickels for the first group and 10 cents for the second group. Thinking about this a little more one finds out that the possibility of 1 nickel and 5 pennies should be chosen only once. So we get (n/10+2) choose 2 ways of change without the nickel/pennies split (i.e. the total number of nickels will be even) and ((n-10)/10+2) choose 2 ways of change with one nickel/pennies split (i.e. the total number of nickels will be odd).
For an arbitrary number n of cents let [n/10] denote the value n/10 rounded down, i.e. the maximal number of dimes that can be used in the change. The cents exceeding the largest multiple of 10 in n can only be changed in maximally two ways: either they are all pennies or - if at least 5 cents remain - one nickel and pennies for the rest. To avoid counting the same way of change several times one can forbid to use any more pennies (for the groups of 10 cents) if there is a nickel in the change of the 'excess'-cents, so only dimes and and nickels for the groups of 10 cents, giving [n/10]+1 ways.
Alltogether one arrives at the following formula for N, the total number of ways for changing n cents:
N1 = ([n/10]+2) choose 2 + ([n/10]+1) choose 2 = ([n/10]+1)^2
[n/10]+1, if n mod 10 >= 5
N2 = {
0, otherwise
N = N1 + N2
Or as Python code:
def change_1_5_10_count(n):
n_10 = n // 10
N1 = (n_10+1)**2
N2 = (n_10+1) if n % 10 >= 5 else 0
return N1 + N2
btw, the computation can be further simplified: N = [([n/5]+2)^2/4], or in Python notation: (n // 5 + 2)**2 // 4.
Almost certainly not for the general case. That's why recursive and bottom-up dynamic programs are used. The modulus operator would provide us with a remainder when dividing the amount by the coin denomination -- meaning we would be using the maximum count of that coin that we can -- but for our solution, we need to count ways of making change when different counts of each coin denomination are used.
Identical intermediate amounts can be reached by using different combinations of coins, and that is what the classic method uses a cache for. O(amount * num_coins):
# Adapted from https://algorithmist.com/wiki/Coin_change#Dynamic_Programming
def coin_change_bottom_up(amount, coins):
cache = [[None] * len(coins) for _ in range(amount + 1)]
for m in range(amount+1):
for i in range(len(coins)):
# There is one way to return
# zero change with the ith coin.
if m == 0:
cache[m][i] = 1
# Base case: the first
# coin (which would be last
# in a top-down recursion).
elif i == 0:
# If this first/last coin
# divides m, there's one
# way to make change;
if m % coins[i] == 0:
cache[m][i] = 1
# otherwise, no way to make change.
else:
cache[m][i] = 0
else:
# Add the number of ways to
# make change for this amount
# without this particular coin.
cache[m][i] = cache[m][i - 1]
# If this coin's denomintion is less
# than or equal to the amount we're
# making change for, add the number
# of ways we can make change for the
# amount reduced by the coin's denomination
# (thus using the coin), again considering
# this and previously seen coins.
if coins[i] <= m:
cache[m][i] += cache[m - coins[i]][i]
return cache[amount][len(coins)-1]
With Python you can leverage the #cache decorator (or #lru_cache) and automatically make a recursive solution into a cached one. For example:
from functools import cache
#cache
def change(amount, coins=(1, 5, 10)):
if coins==(): return amount==0
C = coins[-1]
return sum([change(amount - C*x, coins[:-1]) for x in range(1+(amount//C))])
print(change(27, (1, 5, 10))) # 12
print(change(27, (1, 5))) # 6
print(change(17, (1, 5))) # 4
print(change(7, (1, 5))) # 2
# ch(27, (1, 5, 10)) == ch(27, (1, 5)) + ch(17, (1, 5)) + ch(7, (1, 5))
This will invoke the recursion only for those values of the parameters which the result hasn't been already computed and stored. With #lru_cache, you can even specify the maximum number of elements you allow in the cache.
This will be one of the DP approach for this problem:
def coin_ways(coins, amount):
dp = [[] for _ in range(amount+1)]
dp[0].append([]) # or table[0] = [[]], if prefer
for coin in coins:
for x in range(coin, amount+1):
dp[x].extend(ans + [coin] for ans in dp[x-coin])
#print(dp)
return len(dp[amount])
if __name__ == '__main__':
coins = [1, 5, 10] # 2, 5, 10, 25]
print(coin_ways(coins, 27)) # 12

COLCOIN - Collecting Coins

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]))

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!

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