What algorithm should we use to get the count of n digit numbers such that the product of its digits is p; the special condition here is that none of the digits should be 1;
What i have thought so far is to do a prime factorization of p. Say n=3 and p=24.
we first do a prime factorization of 24 to get : 2*2*2*3.
now i have problem in determining the combinations of these which are
4*2*3 , 2*4*3, .... etc
Even if can do so... how will I scale for n is way smaller than the count of primes.
I am not too sure if thats the right direction... any inputs are welcome.
First, you don't really need full prime decomposition, only decomposition to primes smaller than your base (I guess you mean 10 here but the problem can be generalized to any base). So we only need factorization into the first 4 primes: 2, 3, 5 and 7. If the rest (prime or not) factor is anything bigger than 1, then the problem has 0 solutions.
Now, lets assume that the number p is factored into:
p = 2^d1 * 3^d2 * 5^d3 * 7^d4
and is also composed from the n digits:
p = d(n-1)d(n-2)...d2d1d0
Then, rearranging the digits, is will also be:
p = 2^q2 * 3^q3 * 4^q4 * 5^q3 * ... * 9^q9
where qi >= 0 and q2 + q3 + ... q9 = n
and also (due to the factorization):
for prime=2: d1 = q2 + 2*q4 + q6 + 3*q8
for prime=3: d2 = q3 + q6 + 2*q9
for prime=5: d3 = q5
for prime=7: d4 = q7
So the q5 and q7 are fixed and we have to find all non-negative integer solutions to the equations:
(where the unknowns are the rest qi: q2, q3, q4, q6, q8 and q9)
d1 = q2 + 2*q4 + q6 + 3*q8
d2 = q3 + q6 + 2*q9
n - d3 - d4 = q2 + q3 + q4 + q6 + q8 + q9
For every one of the above solutions, there are several rearrangements of the digits, which can be found by the formula:
X = n! / ( q2! * q3! * ... q9! )
which have to be summed up.
There may be a closed formula for this, using generating functions, you could post it at Math.SE
Example for p=24, n=3:
p = 2^3 * 3^1 * 5^0 * 7^0
and we have:
d1=3, d2=1, d3=0, d4=0
The integer solutions to:
3 = q2 + 2*q4 + q6 + 3*q8
1 = q3 + q6 + 2*q9
3 = q2 + q3 + q4 + q6 + q8 + q9
are (q2, q3, q4, q6, q8, q9) =:
(2, 0, 0, 1, 0, 0)
(1, 1, 1, 0, 0, 0)
which give:
3! / ( 2! * 1! ) = 3
3! / ( 1! * 1! * 1! ) = 6
and 3+6 = 9 total solutions.
Example for p=3628800, n=10:
p = 2^8 * 3^4 * 5^1 * 7^1
and we have:
d1=8, d2=4, d3=1, d4=1
The integer solutions to:
8 = q2 + 2*q4 + q6 + 3*q8
4 = q3 + q6 + 2*q9
8 = q2 + q3 + q4 + q6 + q8 + q9
are (q2, q3, q4, q6, q8, q9) (along with the corresponding digits and the rearrangements per solution):
(5, 0, 0, 0, 1, 2) 22222899 57 10! / (5! 2!) = 15120
(4, 0, 2, 0, 0, 2) 22224499 57 10! / (4! 2! 2!) = 37800
(4, 1, 0, 1, 1, 1) 22223689 57 10! / (4!) = 151200
(3, 2, 1, 0, 1, 1) 22233489 57 10! / (3! 2!) = 302400
(4, 0, 1, 2, 0, 1) 22224669 57 10! / (4! 2!) = 75600
(3, 1, 2, 1, 0, 1) 22234469 57 10! / (3! 2!) = 302400
(2, 2, 3, 0, 0, 1) 22334449 57 10! / (3! 2! 2!) = 151200
(2, 4, 0, 0, 2, 0) 22333388 57 10! / (4! 2! 2!) = 37800
(3, 2, 0, 2, 1, 0) 22233668 57 10! / (3! 2! 2!) = 151200
(2, 3, 1, 1, 1, 0) 22333468 57 10! / (3! 2!) = 302400
(1, 4, 2, 0, 1, 0) 23333448 57 10! / (4! 2!) = 75600
(4, 0, 0, 4, 0, 0) 22226666 57 10! / (4! 4!) = 6300
(3, 1, 1, 3, 0, 0) 22234666 57 10! / (3! 3!) = 100800
(2, 2, 2, 2, 0, 0) 22334466 57 10! / (2! 2! 2! 2!) = 226800
(1, 3, 3, 1, 0, 0) 23334446 57 10! / (3! 3!) = 100800
(0, 4, 4, 0, 0, 0) 33334444 57 10! / (4! 4!) = 6300
which is 2043720 total solutions, if I haven't done any mistakes..
I don't think I'd start by tackling what is known to be a 'hard' problem, computing the prime decomposition. By I don't think I mean my gut feeling, rather than any rigorous computation of complexity, tells me.
Since you are ultimately only interested in the single-digit divisors of p I'd start by dividing p by 2, then by 3, then 4, all the way up to 9. Of course, some of these divisions won't produce an integer result in which case you can discard that digit from further consideration.
For your example of p = 24 you'll get {{2},12}, {{3},8}, {{4},6}, {{6},4}, {{8},3} (ie tuples of divisor and remainder). Now apply the approach again, though this time you are looking for the 2 digit numbers whose digits multiply to the remainder. That is, for {{2},12} you would get {{2,2},6},{{2,3},4},{{2,4},3},{{2,6},2}. As it happens all of these results deliver 3-digit numbers whose digits multiply to 24, but in general it is possible that some of the remainders will still have 2 or more digits and you'll need to trim the search tree at those points. Now go back to {{3},8} and carry on.
Note that this approach avoids having to separately calculate how many permutations of a set of digits you need to consider because it enumerates them all. It also avoids having to consider 2*2 and 4 as separate candidates for inclusion.
I expect you could speed this up with a little memoisation too.
Now I look forward to someone more knowledgeable in combinatorics telling us the closed-form solution to this problem.
You can use dynamic programming approach based on the following formula:
f[ n ][ p ] = 9 * ( 10^(n-1) - 9^(n-1) ), if p = 0
0, if n = 1 and p >= 10
1, if n = 1 and p < 10
sum{ f[ n - 1 ][ p / k ] for 0 < k < 10, p mod k = 0 }, if n > 1
The first case is a separate case for p = 0. This case calculates in O(1), besides helps to exclude k = 0 values from 4th case.
The 2nd and 3rd cases are the dynamic base.
The 4th case k sequentially takes all possible values of the last digit, and we sum up quantities of numbers with product p with last digit k by reducing to the same problem of smaller size.
This will have O( n * p ) running time if you implement dp with memorization.
PS: My answer is for more general problem than OP described. If condition that no digit must be equal to 1 must be satisfied, formulas can be adjusted as follows:
f[ n ][ p ] = 8 * ( 9^(n-1) - 8^(n-1) ), if p = 0
0, if n = 1 and p >= 10 or p = 1
1, if n = 1 and 1 < p < 10
sum{ f[ n - 1 ][ p / k ] for 1 < k < 10, p mod k = 0 }, if n > 1
For the N digit numbers and product of its digits is p;
For example if n = 3 and p =24
Arrangement would be as follow (Permutation)
= (p!)/(p-n)!
= (24!) /(24 -3)!
= (24 * 23 * 22 * 21 )! / 21 !
= (24 * 23 * 22 )
= 12144
So it would be 12144 arrangement can be made
And for Combination is as follow
= (p!)/(n!) * (p-n)!
= (24!) /(3!) * (24 -3)!
= (24 * 23 * 22 * 21 )! / (3!) * 21 !
= (24 * 23 * 22 ) / 6
= 2024
May this will help you
The problems seems contrived but in any case there are upper bounds to what you seen. For example p can have no prime divisor > 7 since it needs to be a single digit ("such that the product of its digits").
Hence suppose p = 1 * 2^a * 3^b * 5^c * 7^d.
2^a can come from ceil(a/3) to 'a' digits. 3^b can come from ceil(b/2) to 'b' digits. 5^c and 7^d can come from 'c' and 'd' digits respectively. The remaining digits can be filled with 1s.
Hence n can range from ceil(a/3)+ceil(b/2)+c+d to infinity while p has a set of fixed values.
Prime factorization feels like the right direction, though you don't need any prime greater than 7, so you can just divide by 2,3,5,7 repeatedly. (No solution if we don't get a prime, or get one > 7).
Once we have the prime factors, p % x and p / x can be implemented as constant time operations (you don't actually need p, you can just keep the prime factors).
My idea is, calculate the combinations with the algorithm below, and the permutations from there is easy.
getCombinations(map<int, int> primeCounts, int numSoFar, string str)
if (numSoFar == n)
if (primeCounts == allZeroes)
addCombination(str);
else
;// do nothing, too many digits
else if (primeCounts[7] >= 1) // p % 7
getCombinations(primeCounts - [7]->1, numSoFar-1, str + "7")
else if (primeCounts[5] >= 1) // p % 5
getCombinations(primeCounts - [5]->1, numSoFar-1, str + "5")
else if (primeCounts[3] >= 2) // p % 9
getCombinations(primeCounts - [3]->2, numSoFar-1, str + "9")
getCombinations(primeCounts - [3]->2, numSoFar-2, str + "33")
else if (primeCounts[2] >= 3) // p % 8
getCombinations(primeCounts - [2]->3, numSoFar-1, str + "8")
getCombinations(primeCounts - [2]->3, numSoFar-2, str + "24")
getCombinations(primeCounts - [2]->3, numSoFar-3, str + "222")
else if (primeCounts[3] >= 1 && primeCounts[2] >= 1) // p % 6
getCombinations(primeCounts - {[2]->1,[3]->1}, numSoFar-1, str + "6")
getCombinations(primeCounts - {[2]->1,[3]->1}, numSoFar-2, str + "23")
else if (primeCounts[2] >= 2) // p % 4
getCombinations(primeCounts - [2]->2, numSoFar-1, str + "4")
getCombinations(primeCounts - [2]->2, numSoFar-2, str + "22")
else if (primeCounts[3] >= 1) // p % 3
getCombinations(primeCounts - [3]->1, numSoFar-1, str + "3")
else if (primeCounts[2] >= 1) // p % 2
getCombinations(primeCounts - [2]->1, numSoFar-1, str + "2")
else ;// do nothing, too few digits
Given the order in which things are done, I don't think there would be duplicates.
Improvement:
You needn't look at p%7 again (deeper down the stack) once you've looked at p%5, since we know it can't be divisible by 7 any more, so a lot of those checks can be optimised away.
primeCounts needn't be a map, it can just be an array of length 4, and it needn't be copied, one can just increase and decrease the values appropriately. Something similar can be done with str as well (character array).
If there were too many digits for getCombinations(..., str + "8"), there's no point in checking "24" or "222". This and similar checks shouldn't be too difficult to implement (just have the function return a bool).
Related
I need help with the following problem.
Given an integer m, I need to find the number of positive integers n and the integers, such that the factorial of n ends with exactly m zeroes.
I wrote this code it works fine and i get the right output, but it take way too much time as the numbers increase.
a = input()
while a:
x = []
m, n, fact, c, j = input(), 0, 1, 0, 0
z = 10*m
t = 10**m
while z - 1:
fact = 1
n = n + 1
for i in range(1, n + 1):
fact = fact * i
if fact % t == 0 and ((fact / t) % 10) != 0:
x.append(int(n))
c = c + 1
z = z - 1
for p in range(c):
print x[p],
a -= 1
print c
Could someone suggest me a more efficient way to do this. Presently, it takes 30 seconds for a test case asking for numbers with 250 trailing zeros in its factorial.
Thanks
To get number of trailing zeroes of n! efficiently you can put
def zeroes(value):
result = 0;
d = 5;
while (d <= value):
result += value // d; # integer division
d *= 5;
return result;
...
# 305: 1234! has exactly 305 trailing zeroes
print zeroes(1234)
In order to solve the problem (what numbers have n trailing zeroes in n!) you can use these facts:
number of zeroes is a monotonous function: f(x + a) >= f(x) if a >= 0.
if f(x) = y then x <= y * 5 (we count only 5 factors).
if f(x) = y then x >= y * 4 (let me leave this for you to prove)
Then implement binary search (on monotonous function).
E.g. in case of 250 zeroes we have the initial range to test [4*250..5*250] == [1000..1250]. Binary search narrows the range down into [1005..1009].
1005, 1006, 1007, 1008, 1009 are all numbers such that they have exactly 250 trainling zeroes in factorial
Edit I hope I don't spoil the fun if I (after 2 years) prove the last conjecture (see comments below):
Each 5**n within facrtorial when multiplied by 2**n produces 10**n and thus n zeroes; that's why f(x) is
f(x) = [x / 5] + [x / 25] + [x / 125] + ... + [x / 5**n] + ...
where [...] stands for floor or integer part (e.g. [3.1415926] == 3). Let's perform easy manipulations:
f(x) = [x / 5] + [x / 25] + [x / 125] + ... + [x / 5**n] + ... <= # removing [...]
x / 5 + x / 25 + x / 125 + ... + x / 5**n + ... =
x * (1/5 + 1/25 + 1/125 + ... + 1/5**n + ...) =
x * (1/5 * 1/(1 - 1/5)) =
x * 1/5 * 5/4 =
x / 4
So far so good
f(x) <= x / 4
Or if y = f(x) then x >= 4 * y Q.E.D.
Focus on the number of 2s and 5s that makes up a number. e.g. 150 is made up of 2*3*5*5, there 1 pair of 2&5 so there's one trailing zero. Each time you increase the tested number, try figuring out how much 2 and 5s are in the number. From that, adding up previous results you can easily know how much zeros its factorial contains.
For example, 15!=15*...*5*4*3*2*1, starting from 2:
Number 2s 5s trailing zeros of factorial
2 1 0 0
3 1 0 0
4 2 0 0
5 2 1 1
6 3 1 1
...
10 5 2 2
...
15 7 3 3
..
24 12 6 6
25 12 8 8 <- 25 counts for two 5-s: 25 == 5 * 5 == 5**2
26 13 8 8
..
Refer to Peter de Rivaz's and Dmitry Bychenko's comments, they have got some good advices.
You are given a function let’s say bin() which will generate 0 or 1 with equal probability. Now you are given a range of contiguous integers say [a,b] (a and b inclusive).
Write a function say rand() using bin() to generate numbers within range [a,b] with equal probability
The insight you need is that your bin() function returns a single binary digit, or "bit". Invoking it once gives you 0 or 1. If you invoke it twice you get two bits b0 and b1 which can be combined as b1 * 2 + b0, giving you one of 0, 1, 2 or 3 with equal probability. If you invoke it thrice you get three bits b0, b1 and b2. Put them together and you get b2 * 2^2 + b1 * 2 + b0, giving you a member of {0, 1, 2, 3, 4, 5, 6, 7} with equal probability. And so on, as many as you want.
Your range [a, b] has m = b-a+1 values. You just need enough bits to generate a number between 0 and 2^n-1, where n is the smallest value that makes 2^n-1 greater than or equal to m. Then just scale that set to start at a and you're good.
So let's say you are given the range [20, 30]. There are 11 numbers there from 20 to 30 inclusive. 11 is greater than 8 (2^3), but less than 16 (2^4), so you'll need 4 bits. Use bin() to generate four bits b0, b1, b2, and b3. Put them together as x = b3 * 2^3 + b2 * 2^2 + b1 * 2 + b0. You'll get a result, x, between 0 and 15. If x > 11 then generate another four bits. When x <= 11, your answer is x + 20.
Help, but no code:
You can shift the range [0,2 ** n] easily to [a,a+2 ** n]
You can easily produce an equal probability from [0,2**n-1]
If you need a number that isn't a power of 2, just generate a number up to 2 ** n and re-roll if it exceeds the number you need
Subtract the numbers to work out your range:
Decimal: 20 - 10 = 10
Binary : 10100 - 01010 = 1010
Work out how many bits you need to represent this: 4.
For each of these, generate a random 1 or 0:
num_bits = 4
rand[num_bits]
for (x = 0; x < num_bits; ++x)
rand[x] = bin()
Let's say rand[] = [0,1,0,0] after this. Add this number back to the start of your range.
Binary: 1010 + 0100 = 1110
Decimal: 10 + 4 = 14
You can always change the range [a,b] to [0,b-a], denote X = b - a. Then you can define a function rand(X) as follows:
function int rand(X){
int i = 1;
// determine how many bits you need (see above answer for why)
while (X < 2^i) {
i++;
}
// generate the random numbers
Boolean cont = true;
int num = 0;
while (cont == true) {
for (j = 1 to i) {
// this generates num in range [0,2^i -1] with equal prob
// but we need to discard if num is larger than X
num = num + bin() * 2^j;
}
if (num <= X) { cont = false}
}
return num;
}
I am trying to get as good an estimate of pi as I can using the Chudnovsky algorithm in Python. This algorithm implies getting the square root of 640 320.
After doing some research, I found a quite effective way to compute square roots; the method is called "digit-by-digit calculation" (see here). So, after trying to implement it, I found out that the first 13 decimals are correct, and then I get strange results (the next one is a 0 instead of a 4, and then the next 'digit' is 128, then -1024...)
I tried checking my function, but it looks fine to me (besides, I would probably not find the correct first 13 decimals otherwise). Thus, my question is : are there some limits in this digit-by-digit calculation method?
If, by any chance, you would like to see my code, here it is:
def sqrt(input_number,accuracy):
"""input_number is a list that represents a number we want to get the square root of.
For example, 12.56 would be [[1,2], [5,6], '+']"""
if input_number[2]!="+":
raise ValueError("Cannot find the real square root of a negative number: '"+pl(input_number)+"'")
"""Below creates the right number of elements for the required accuracy of the
square root"""
if len(input_number[0])%2==1:
input_number[0].insert(0,0)
if len(input_number[1])<2*accuracy:
for i in range(2*accuracy-len(input_number[1])):
input_number[1].append(0)
if len(input_number[1])%2==1:
input_number[1].append(0)
# Below makes the pairs of digits required in the algorithm
pairs=[[10*input_number[0][2*i]+input_number[0][2*i+1] for i in range(int(len(input_number[0])/2))],[10*input_number[1][2*i]+input_number[1][2*i+1] for i in range(int(len(input_number[1])/2))]]
"""Performs the algorithm, where c,x,y and p have the same definition
as on the Wikipedia link above. r is the remainder. pairs[0] is the pairs
of digits before the decimal dot, and pairs[1] represents the pairs of
digits after the dot. square_root is the computed square root of input_number."""
p=0
r=0
square_root=[[],[],"+"]
for i in range(len(pairs[0])):
c=100*r+pairs[0][i]
x=int((-20*p+(400*p**2+4*c)**.5)/2)
y=20*p*x+x**2
r=c-y
p=10*p+x
square_root[0].append(x)
for i in range(len(pairs[1])):
print(p,r,c)
c=100*r+pairs[1][i]
x=int((-20*p+(400*p**2+4*c)**.5)/2)
y=20*p*x+x**2
r=c-y
p=10*p+x
square_root[1].append(x)
return square_root
The problem is this code.
x = int((-20 * p + (400 * p ** 2 + 4 * c) ** .5) / 2)
This code performs Floating-point subtraction. It causes loss of significance, because of two close numbers are subtracted.
>>> p = 10**15
>>> c = 10**15
>>> x = (-20 * p + (400 * p ** 2 + 4 * c) ** .5) / 2
>>> x
0.0
so, you should use integer sqrt instead of **.5. and change loop like this.
for i in range(len(pairs[0])):
c = 100 * r + pairs[0][i]
#x = int((-20 * p + (400 * p ** 2 + 4 * c) ** .5) / 2)
x = (-20 * p + isqrt(400 * p ** 2 + 4 * c)) // 2
y = 20 * p * x + x ** 2
r = c - y
p = 10 * p + x
square_root[0].append(x)
for i in range(len(pairs[1])):
#print(p,r,c)
c = 100 * r + pairs[1][i]
#x = int((-20 * p + (400 * p ** 2 + 4 * c) ** .5) / 2)
x = (-20 * p + isqrt(400 * p ** 2 + 4 * c)) // 2
y = 20 * p * x + x ** 2
r = c - y
p = 10 * p + x
square_root[1].append(x)
and define isqrt -- the integer sqrt function
# from http://stackoverflow.com/questions/15390807/integer-square-root-in-python
def isqrt(n):
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x
Then, you could get an accurated value of sqrt(2).
>>> print( sqrt([[2], [0], '+'], 25) )
[[1], [4, 1, 4, 2, 1, 3, 5, 6, 2, 3, 7, 3, 0, 9, 5, 0, 4, 8, 8, 0, 1, 6, 8, 8, 7], '+']
I'm doing a Ruby kata that asks me to find the sum of the digits of all the numbers from 1 to N (both ends included).
So if I had these inputs, I would get these outputs:
For N = 10 the sum is 1+2+3+4+5+6+7+8+9+(1+0) = 46
For N = 11 the sum is 1+2+3+4+5+6+7+8+9+(1+0)+(1+1) = 48
For N = 12 the sum is 1+2+3+4+5+6+7+8+9+(1+0)+(1+1) +(1+2)= 51
Now I know in my head what needs to be done. Below is the code that I have to solve this problem:
def solution(n)
if n <= 9
return n if n == 1
solution(n-1) + n
elsif n >= 10
45 + (10..n) #How can I grab the ones,tenths, and hundreds?
end
end
Basically everything is fine until I hit over 10.
I'm trying to find some sort of method that could do this. I searched Fixnum and Integer but I haven't found anything that could help me. I want is to find something like "string"[0] but of course without having to turn the integer back in forth between a string and integer. I know that there is a mathematical relationship there but I'm having a hard time trying to decipher that.
Any help would be appreciated.
You can use modulo and integer division to calculate it recursively:
def sum_digits(n)
return n if n < 10
(n % 10) + sum_digits(n / 10)
end
sum_digits(123)
# => 6
A beginner would probably do this:
123.to_s.chars.map(&:to_i)
# => [1, 2, 3]
but a more thoughtful person would do this:
n, a = 123, []
until n.zero?
n, r = n.divmod(10)
a.unshift(r)
end
a
# => [1, 2, 3]
Rather than computing the sum of the digits for each number in the range, and then summing those subtotals, I have computed the total using combinatorial methods. As such, it is much more efficient than straight enumeration.
Code
SUM_ONES = 10.times.with_object([]) { |i,a| a << i*(i+1)/2 }
S = SUM_ONES[9]
def sum_digits_nbrs_up_to(n)
pwr = n.to_s.size - 1
tot = n.to_s.chars.map(&:to_i).reduce(:+)
sum_leading_digits = 0
pwr.downto(0).each do |p|
pwr_term = 10**p
leading_digit = n/pwr_term
range_size = leading_digit * pwr_term
tot += sum_leading_digits * range_size +
sum_digits_to_pwr(leading_digit, p)
sum_leading_digits += leading_digit
n -= range_size
end
tot
end
def sum_digits_to_pwr(d, p)
case
when d.zero? && p.zero?
0
when d.zero?
10**(p-1) * S * d * p
when p.zero?
10**p * SUM_ONES[d-1]
else
10**p * SUM_ONES[d-1] + 10**(p-1) * S * d * p
end
end
Examples
sum_digits_nbrs_up_to(456) #=> 4809
sum_digits_nbrs_up_to(2345) #=> 32109
sum_digits_nbrs_up_to(43021) #=> 835759
sum_digits_nbrs_up_to(65827359463206357924639357824065821)
#=> 10243650329265398180347270847360769369
These calculations were all essentially instantaneous. I verified the totals for the first three examples by straight enumeration, using #sawa's method for calculating the sum of digits for each number in the range.
Explanation
The algorithm can best be explained with an example. Suppose n equals 2345.
We begin by defining the following functions:
t(n) : sum of all digits of all numbers between 1 and n, inclusive (the answer)
sum(d): sum of all digits between 1 and d, inclusive, (for d=1..9, sum(d) = 0, 1, 3, 6, 10, 15, 21, 28, 36, 45).
g(i) : sum of digits of the number i.
f(i,j): sum of all digits of all integers between i and j-1, inclusive.
g(m) : sum of digits of the number m.
h(d,p): sum of all digits of all numbers between 0 and d*(10^p)-1 (derived below).
Then (I explain the following below):
t(2345) = f(0-1999)+f(2000-2299)+f(2300-2339)+f(2340-2344)+g(2345)
f( 0-1999) = h(2,3) = h(2,3)
f(2000-2299) = 2 * (2299-2000+1) + h(3,2) = 600 + h(3,2)
f(2300-2339) = (2+3) * (2339-2300+1) + h(4,1) = 200 + h(4,1)
f(2340-2344) = (2+3+4) * (2344-2340+1) + h(5,0) = 45 + h(5,0)
g(2345) = 2+3+4+5 = 14
so
t(2345) = 859 + h(2,3) + h(3,2) + h(4,1) + h(5,0)
First consider f(2000-2299). The first digit, 2, appears in every number in the range (2000..2299); i.e., 300 times. The remaining three digits contribute (by definition) h(3,2) to the total:
f(2000-2299) = 2 * 300 + h(3,2)
For f(2300-2339) the first two digits, 2 and 3, are present in all 40 numbers in the range (2300..2339) and the remaining two digits contribute h(4,1) to the total:
f(2300-2339) = 5 * 40 + h(4,1)
For f(2340-2344), the first three digits, '2,3and4, are present in all four number in the range ``(2340-2344) and the last digit contributes h(5,0) to the total.
It remains to derive an expression for computing h(d,p). Again, this is best explained with an example.
Consider h(3,2), which is the sum of the all digits of all numbers between 0 and 299.
First consider the sum of digits for the first digit. 0, 1 and 2 are each the first digit for 100 numbers in the range 0-299. Hence, the first digit, summed, contributes
0*100 + 1*100 + 2*100 = sum(2) * 10^2
to the total. We now add the sum of digits for the remaining 2 digits. The 300 numbers each have 2 digits in the last two positions. Each of the digits 0-9 appears in 1/10th of 2 * 300 = 600 digits; i.e, 60 times. Hence, the sum of all digits in last 2 digit positions, over all 300 numbers, equals:
sum(9) * 2 * 300 / 10 = 45 * 2 * 30 = 2700.
More generally,
h(d,p) = sum(d-1) * 10**p + sum(9) * d * p * 10**(p-1) if d > 0 and p > 0
= sum(d-1) * 10**p if d > 0 and p == 0
= sum(9) * d * p * 10**(p-1) if d == 0 and p > 0
= 0 if d == 0 and p == 0
Applying this to the above example, we have
h(2,3) = sum(1) * 10**3 + (45 * 2 * 3) * 10**2 = 1 * 1000 + 270 * 100 = 28000
h(3,2) = sum(2) * 10**2 + (45 * 3 * 2) * 10**1 = 3 * 100 + 270 * 10 = 3000
h(4,1) = sum(3) * 10**1 + (45 * 4 * 1) * 10**0 = 6 * 10 + 180 * 1 = 240
h(5,0) = sum(4) * 10**0 = 10 * 1 = 10
Therefore
t(2345) = 859 + 28000 + 3000 + 240 + 10 = 32109
The code above implements this algorithm in a straightforward way.
I confirmed the results for the first three examples above by using using #sawa's code to determine the sum of the digits for each number in the range and then summed those totals:
def sum_digits(n)
a = []
until n.zero?
n, r = n.divmod(10)
a.unshift(r)
end
a.reduce(:+)
end
def check_sum_digits_nbrs_up_to(n)
(1..n).reduce(0) {|t,i| t + sum_digits(i) }
end
check_sum_digits_nbrs_up_to(2345) #=> 32109
Let's say I have a number of base 3, 1211. How could I check this number is divisible by 2 without converting it back to base 10?
Update
The original problem is from TopCoder
The digits 3 and 9 share an interesting property. If you take any multiple of 3 and sum its digits, you get another multiple of 3. For example, 118*3 = 354 and 3+5+4 = 12, which is a multiple of 3. Similarly, if you take any multiple of 9 and sum its digits, you get another multiple of 9. For example, 75*9 = 675 and 6+7+5 = 18, which is a multiple of 9. Call any digit for which this property holds interesting, except for 0 and 1, for which the property holds trivially.
A digit that is interesting in one base is not necessarily interesting in another base. For example, 3 is interesting in base 10 but uninteresting in base 5. Given an int base, your task is to return all the interesting digits for that base in increasing order. To determine whether a particular digit is interesting or not, you need not consider all multiples of the digit. You can be certain that, if the property holds for all multiples of the digit with fewer than four digits, then it also holds for multiples with more digits. For example, in base 10, you would not need to consider any multiples greater than 999.
Notes
- When base is greater than 10, digits may have a numeric value greater than 9. Because integers are displayed in base 10 by default, do not be alarmed when such digits appear on your screen as more than one decimal digit. For example, one of the interesting digits in base 16 is 15.
Constraints
- base is between 3 and 30, inclusive.
This is my solution:
class InterestingDigits {
public:
vector<int> digits( int base ) {
vector<int> temp;
for( int i = 2; i <= base; ++i )
if( base % i == 1 )
temp.push_back( i );
return temp;
}
};
The trick was well explained here : https://math.stackexchange.com/questions/17242/how-does-base-of-a-number-relate-to-modulos-of-its-each-individual-digit
Thanks,
Chan
If your number k is in base three, then you can write it as
k = a0 3^n + a1 3^{n-1} + a2 3^{n-2} + ... + an 3^0
where a0, a1, ..., an are the digits in the base-three representation.
To see if the number is divisible by two, you're interested in whether the number, modulo 2, is equal to zero. Well, k mod 2 is given by
k mod 2 = (a0 3^n + a1 3^{n-1} + a2 3^{n-2} + ... + an 3^0) mod 2
= (a0 3^n) mod 2 + (a1 3^{n-1}) mod 2 + ... + an (3^0) mod 2
= (a0 mod 2) (3^n mod 2) + ... + (an mod 2) (3^0 mod 2)
The trick here is that 3^i = 1 (mod 2), so this expression is
k mod 2 = (a0 mod 2) + (a1 mod 2) + ... + (an mod 2)
In other words, if you sum up the digits of the ternary representation and get that this value is divisible by two, then the number itself must be divisible by two. To make this even cooler, since the only ternary digits are 0, 1, and 2, this is equivalent to asking whether the number of 1s in the ternary representation is even!
More generally, though, if you have a number in base m, then that number is divisible by m - 1 iff the sum of the digits is divisible by m. This is why you can check if a number in base 10 is divisible by 9 by summing the digits and seeing if that value is divisible by nine.
You can always build a finite automaton for any base and any divisor:
Normally to compute the value n of a string of digits in base b
you iterate over the digits and do
n = (n * b) + d
for each digit d.
Now if you are interested in divisibility you do this modulo m instead:
n = ((n * b) + d) % m
Here n can take at most m different values. Take these as states of a finite automaton, and compute the transitions depending on the digit d according to that formula. The accepting state is the one where the remainder is 0.
For your specific case we have
n == 0, d == 0: n = ((0 * 3) + 0) % 2 = 0
n == 0, d == 1: n = ((0 * 3) + 1) % 2 = 1
n == 0, d == 2: n = ((0 * 3) + 2) % 2 = 0
n == 1, d == 0: n = ((1 * 3) + 0) % 2 = 1
n == 1, d == 1: n = ((1 * 3) + 1) % 2 = 0
n == 1, d == 2: n = ((1 * 3) + 2) % 2 = 1
which shows that you can just sum the digits 1 modulo 2 and ignore any digits 0 or 2.
Add all the digits together (or even just count the ones) - if the answer is odd, the number is odd; if it's even, the nmber is even.
How does that work? Each digit from the number contributes 0, 1 or 2 times (1, 3, 9, 27, ...). A 0 or a 2 adds an even number, so no effect on the oddness/evenness (parity) of the number as a whole. A 1 adds one of the powers of 3, which is always odd, and so flips the parity). And we start from 0 (even). So by counting whether the number of flips is odd or even we can tell whether the number itself is.
I'm not sure on what CPU you have a number in base-3, but the normal way to do this is to perform a modulus/remainder operation.
if (n % 2 == 0) {
// divisible by 2, so even
} else {
// odd
}
How to implement the modulus operator is going to depend on how you're storing your base-3 number. The simplest to code will probably be to implement normal pencil-and-paper long division, and get the remainder from that.
0 2 2 0
_______
2 ⟌ 1 2 1 1
0
---
1 2
1 1
-----
1 1
1 1
-----
0 1 <--- remainder = 1 (so odd)
(This works regardless of base, there are "tricks" for base-3 as others have mentioned)
Same as in base 10, for your example:
1. Find the multiple of 2 that's <= 1211, that's 1210 (see below how to achieve it)
2. Substract 1210 from 1211, you get 1
3. 1 is < 10, thus 1211 isn't divisible by 2
how to achieve 1210:
1. starts with 2
2. 2 + 2 = 11
3. 11 + 2 = 20
4. 20 + 2 = 22
5. 22 + 2 = 101
6. 101 + 2 = 110
7. 110 + 2 = 112
8. 112 + 2 = 121
9. 121 + 2 = 200
10. 200 + 2 = 202
... // repeat until you get the biggest number <= 1211
it's basically the same as base 10 it's just the round up happens on 3 instead of 10.