I wrote this function below in Python and I am expecting to see 4 as the result but get 2. Why is that?
Here is my function:
def persistence(n):
if 0 <= n <= 9:
return n
else:
result = 0
counter = 0
while True:
result += n % 10 * persistence(n // 10)
counter += 1
if result > 9:
n = result
result = 0
continue
return counter
print(persistence(999)) // Output should be 4 but gives me 2
I know where the problem exactly happens. It is in the line in which I wrote result += n % 10 * persistence(n // 10). when I debug it in the first iteration, instead of giving me the number 729 (the multiplication of 9 * 9 * 9) it gives me 18. Why is that? What is wrong with my code that instead of getting 729 as the output for result in the first iteration I get 18 and therefore the value of persistence(999) is not what I expect it to be?
cydar2500 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.