Looking for an efficient way to multiply "powered digits"

53 Views Asked by At

For a program, I have numbers expressed as a vector of "powered digits". The first element is the power of $0$ (number of $0$ in the number, usually $0$), the second is power of $1$, number of $1$s, and so on $$(a,b,c,d,e,f,g,h,i,j)$$ for $$0^a 1^b 2^c 3^d 4^e 5^f 6^g 7^h 8^i 9^j$$

For instance the number $11222346889$ is expressed as $(0,2,3,1,1,0,1,2,1)$

Then we multiply all the powered digits together, to get a new vector $$0^a\cdot 1^b\cdot 2^c\cdot 3^d\cdot 4^e\cdot 5^f\cdot 6^g\cdot 7^h\cdot 8^i\cdot 9^j \implies 0^{a'} 1^{b'} 2^{c'} 3^{d'} 4^{e'} 5^{f'} 6^{g'} 7^{h'} 8^{i'} 9^{j'}$$ (usually $a$ is $0$, otherwise the product of digits gives immediately $0$, obviously)

With our example (gives $331776$): $$(0,2,3,1,1,0,1,2,1) \implies (0,1,0,2,0,0,1,2,0,0)$$

Numbers can be very large ($b$, $c$, ... can be in the millions), and maybe the multiplication from that kind of "powered digits" vector would be faster than doing the actual multiplication of the millions of digits using a arbitrary large integers library (it's slow!).

The problem is not only the calculation, but also the generated number (product of digits) will also be very large - if we could get directly some kind of vector as explained above, that would dramatically improve performances ; instead of a megabyte number, we would just have to deal with a 10 elements vector.

Question

Is there an efficient way to multiply all the digits together using this method of "powered digits" (or any other method)?

(In other terms, the current time complexity of the program is $O(s = c+d+e+f+g+h+i+j)$. If we could get that down to the $O(\log(s))$ that would be great!)

1

There are 1 best solutions below

2
On

(1) You can first factorize them to prime bases like $8^i=2^{3i}$ or $6^g=2^g\times3^g$.

(2) Combine similar prime bases and calculate the combined exponents like $2^{c+2e+g+3i}$.

(3) Find the binary representation of the exponents like $2^{11}=2^{(1011)_2}$.

(4) Calculate the primes with the exponents recursively like $2^{11}=2^1\times2^2\times2^4=2^{1\times(1)_2}\times2^{1\times(10)_2}\times2^{0\times(100)_2}\times2^{1\times(1000)_2}$. The complexity is $O(log(n))$.

(4.1) Similar exponents can be combined as well.

(5) Multiply the products of the primes with exponents to get the final result.