so the problem I have is that there is two integers (a, b) that is in [1, 10^16] interval and I need to do find out how many digits will number a^b have? Those numbers are too big for saving them on single variables, and if I write them on Array it would take a lot of time.
Is there a way to count the number a^b number of digits with some kind of formula or any simpler way then Arrays?
karakfa has it right.
The base-k
logarithm of a number n
, rounded up to the nearest whole number, will give you the number of digits required to represent n
in base k
.
EDIT: as pointed out in comments, it should not be rounded up, but rounded down and then incremented by one. This accounts for round powers of 10 having an extra digit.
If your number is a^b
then take the base-10 logarithm, log a^b
and use the laws of logarithms to simplify as b log a
. Note that this simplification happens inside the ceiling
function so the simplification is valid. Computing log a
should not be an issue (it will be between 0 and 16) and b
is known. Just make sure to round after multiplying, not before.
Note that limited precision of floating-point numbers may introduce some errors into this method. If the true value of b x log a
is different from the nearest floating-point representation of b x log a
in such a way that they fall on different sides of an integer, the method fails. You can possibly detect when you are close to this condition and remediate it somehow.