How do I count how many digits, has a result of an operation?

Asked

Viewed 41 times

-1

I have an operation that results in some number.

Example:

25**7 = 6103515625

The result has 10 digits.

I want to run the automatic count of the number of digits of the result in any operation.

  • 1

    The code presented in the answer is inefficient and does not work with negative numbers. If you want to quickly calculate the number of digits of an integer in base 10 use the formula floor(log10(abs(n))+1). Take the example: https://ideone.com/vVXmSu

  • 1

    Complementing the @Augustovasques, log(a ** b) is equal to b * log(a), that is, for this case does not even need to do the math (it can make a difference if the numbers start to get too big - and in this case the solution below becomes even more inefficient). Going further, you can take advantage of the properties of logarithms to simplify other operations as well, such as multiplication and division. Finally, there is a link with better answers: https://answall.com/q/271949/112052

1 answer

-1


Use the native function len().

First transform the result from Integer to String, with str(), and call the function len() for your result variable, for example:

resultado =  str(25**7)
 
qtdNumeros = len(resultado)
  • TypeError: object of type 'int' has no len()

  • Corrected answer, by carelessness I ended up forgetting this part.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.