-4

What's the fastest way to determine the number of digits in a number?

Would it be like so:

const val = 10030504;
const numOfDigits = math.floor(math.divide(val, 10));

or perhaps faster to just convert to a string a get a length:

const s = String(val);
const numOfDigits = s.slice(0, s.indexOf('.')).length;

using string manipulations feels wrong.

  • if someone could add the tag base-10 that'd be great.. – Alexander Mills Nov 27 '22 at 20:34
  • 2
    This is not a math question as it is dependent on the computer and language used. I think the first does not work. Wouldn't it return $1003050?$ Whether a string convert is faster or slower than a log function is definitely not math. – Ross Millikan Nov 27 '22 at 20:38
  • Yeah you're right, so I guess the mathy part of the OP is how to do it without string manipulation - thanks – Alexander Mills Nov 27 '22 at 20:38
  • 1
    If you search for number of digits on this site you will find the formula based on rounding the base 10 log. – Ross Millikan Nov 27 '22 at 20:39
  • 1
    The logarithm formula might fail in the case of a number very near a power of ten and limited precision. Modern tools can store huge numbers and then, the number of digits can simply be counted. – Peter Nov 27 '22 at 21:20
  • 1
    If you want to use math, the number of digits of $x$ is : $$\lfloor \log(x) \rfloor + 1$$ Imagine you want the number of digits of $2^{1000}$. – Essaidi Nov 27 '22 at 21:21
  • @Essaidi yeah a string implementation seems faster sadly – Alexander Mills Nov 28 '22 at 01:40
  • I don't see why the question got a downvote, I like this question – Alexander Mills Nov 28 '22 at 01:40

1 Answers1

1

The comments discuss the (software) vulnerability to rounding errors of taking logarithms, base $10$.

Generally, programming languages such as Java, c, or Python, provide BigInteger facilities for just such a situation (i.e. when rounding errors must be avoided). Presumably, positive integers as large as $(10)^{(1000)}$ are routinely handled.

So, you can set the corresponding number to an object $A$ of the BigInteger class. Then, you can create a 2nd BigInteger object $B = 10.$

You can then determine exactly whether $B > A$. If not, multiply $B = B \times 10,$ and re-check whether $B > A$. Assuming that $A < (10)^{(1000)}$, your (very simple) program should routinely find the smallest value of $B$, using this algorithm, such that $B > A$.

Assuming that you maintain a counter $I1$, then if $(10)^{(I1)}$ is the smallest value of $B$ such that $B > A$, then $A$ has exactly $I1$ digits.

user2661923
  • 35,619
  • 3
  • 17
  • 39