0
$\begingroup$

Sorry for the strange title, as I don't really know the proper terminology.

I need a formula that returns 1 if the supplied value is anything from 10 to 99, returns 10 if the value is anything from 100 to 999, returns 100 if the value is anything from 1000 to 9999, and so on.

I will be translating this to code and will ensure the value is never less than 1, in case that changes anything.

It's probably something really simple but I can't wrap my head around a nice way to do this so... thanks!

$\endgroup$
  • 3
    $\begingroup$ Try logarithms (and rounding)! $\endgroup$ – Babelfish May 9 at 7:41
  • 2
    $\begingroup$ Unless time is absolutely of the essence for this operation, the best way to do it is to convert the number to a string and then take its length. This is robust and legible. Note that the mathematical functions below may suffer from floating point errors. $\endgroup$ – Mees de Vries May 9 at 12:59
  • $\begingroup$ @MeesdeVries: It's not only robust and legible; it is way shorter and probably way faster (using floating-point operations here is slow and stupid)! $\endgroup$ – user21820 May 11 at 14:32
4
$\begingroup$

I think your function is $$f(x) = 10^{\left \lfloor \log_{10}(x) \right \rfloor - 1}$$ where $\lfloor r \rfloor$ denotes the largest integer less than or equal to $r$.

$\endgroup$
2
$\begingroup$

Is a mathematical formula really needed ? Or a function (in the sense of a programming language) that does this job ok? As you say you are going to translate this into code it is simpler to directly translate your description to code, without having to find a mathematical formula

Here is it in Python: (you may have to handle numbers less than 10 differently)

def mylog(x):

#assumes x is a positive integer between 10 and 10^25

tenpowers = [10**k for k in range(25)]

for k in range(25):

      if x-1 < tenpowers[k]:

           return  tenpowers[k-1]
$\endgroup$
0
$\begingroup$

$f(x) = 10^{[\log_{10} x]-1}$ where $[x]$ denotes floor

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.