# Logarithm to get the first digit of a number

Hello:

I wrote this programme to get the first and last digits of a given number. However I don’t quite understand the formula to get the first digit. So would appreciate clarification as I forgot logarithms that I learned at secondary school a long time ago.

Here’s the programme:

``````import math

number = 23456

lastNumber = number % 10

firstNumber = number // 10 ** int(math.log(number, 10))

print("The first number is: ", firstNumber)
print("The last number is:", lastNumber)
``````

This log function does it’s job and prints:

``````The first number is:  2
The last number is: 6
``````

I’m having trouble following you.

Are you sure you aren’t confusing logarithm with algorithm?

.

The programme I wrote works with the formula and returns the first digit of a given number with the log function. So it’s it’s the log function I’m referring to. I just wanted clarification on the formula. I just added what the programme prints to be clearer. Thanks in advance.

23456 = 2.3456 x 10^4. If you take the log of this number, then you will get the log of 2.3456 plus 4 ( the log of 10^4 is 4).

The log of 2.3456 will be a decimal less than 1, so the int () or integer value will just be the 4.

10^4 is 10000, so if you use // (floor division) of the number by that, you will get the integer part of 2.3456, which is 2 (the first digit of the number).

I hope this explanation isn’t too confusing.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.