Python Code Optimization: Checking if Factorial Ends with Zero
The given code calculates the factorial of a number and checks if the factorial ends with a 0. However, there are some errors and unnecessary code that can be improved. Below is the modified code:
def TEST_DO_NOT_CHANGE(n):
factorial = 1
for i in range(1, n+1):
factorial *= i
if factorial % 10 == 0:
return 1
return 0
if __name__ == "__main__":
print(TEST_DO_NOT_CHANGE(3))
print(TEST_DO_NOT_CHANGE(5))
Changes made:
- Removed the unnecessary
print(n)statement. - Initialized
factorialto 1 instead of None. - Moved the
return 1inside the loop when a factorial ends with 0, as there is no need to continue calculating. - Returned 0 outside the loop if the factorial does not end with 0.
This optimized version is more efficient as it avoids unnecessary calculations and returns the result immediately when a factorial ending with 0 is found.
原文地址: https://www.cveoy.top/t/topic/pavW 著作权归作者所有。请勿转载和采集!