I don’t know how to get over this problem with while loop. So basically I want to return the number of zeros at the end of a number’s factorial.
JavaScript
x
16
16
1
import math
2
3
4
def zeros(n):
5
total_zero = 0
6
n = math.factorial(n)
7
while str(n)[-1] == '0': # to check if the last number is 0 or not
8
n = n * 0.1
9
total_zero += 1
10
11
return total_zero
12
13
14
output = zeros(30)
15
print(output)
16
After the while loop runs only 1 time, it breaks; I don’t know why.
Help would be very appreciated. Thanks!
Advertisement
Answer
After multiplying your value by 0.1
it becomes a float
, and it’s string representation becomes the scientific notation 2.6525285981219107e+31
which doesn’t end by a 1
You’d better do the integer division by 10 to keep an int
JavaScript
1
19
19
1
def zeros(n):
2
total_zero = 0
3
n = math.factorial(n)
4
while str(n)[-1] == '0': # to check if the last number is 0 or not
5
n = n // 10
6
total_zero += 1
7
print(f"testting {str(n)}")
8
return total_zero
9
10
>> zeros(30)
11
testting 26525285981219105863630848000000
12
testting 2652528598121910586363084800000
13
testting 265252859812191058636308480000
14
testting 26525285981219105863630848000
15
testting 2652528598121910586363084800
16
testting 265252859812191058636308480
17
testting 26525285981219105863630848
18
7
19
Better You can also use str.rstrip
: you remove the leading zeros and check the length difference
JavaScript
1
4
1
def zeros(n):
2
value = str(math.factorial(n))
3
return len(value) - len(value.rstrip("0"))
4