I have written a Happy number program using an array, help me how to calculate Time Complexity? Any number will be called a happy number if, after repeatedly replacing it with a number equal to the sum of the square of all of its digits, leads us to number ‘1’. All other (not-happy) numbers will never reach ‘1’. Instead, they will be stuck in a cycle of numbers which does not include ‘1’.
def happy(num):
ls = []
result = 0
while True:
result = sqr_digits(num)
if result == 1:
return True
elif result in ls:
return False # not happy
else:
ls.append(result)
num = result
def sqr_digits(num):
result = 0
while(num > 0):
digit = num % 10
result += digit ** 2
num //= 10
return result
num = 145
print(happy(num))
[Note: While answering the question, I forgot that your code is using
digit^2, but I've just provided the solution based ondigit. The complexity calculation mechanism is same. If you read the answer, you can easily find out the complexity fordigit^2by yourself. I'll update the answer, when I get sometime. Hope you wouldn't mind]Well, if there is a number
n(base 10), then it can have at mostlog10(n) + 1digits. I hope, i would not have explain it...just google ithow many digits in a 10 based number and how to find it using log.Now, let's explain the complexity of the provided algo:
The algo will only be stopped when the sum turns into a single digit.
So, we can calculate the number of digits, we've to add and that'll be the complexity ultimately.
Exactly calculate the complexity of this algo is not possible, but we can calcuate the complexity of worst case...what would could be max number with
3 digits, of course999, so we'll always considerd ninesin ad digitsnumber.I guess, you can see where this is going. The total digits number can be written as:
So, we can see that the ultimate complexity is determined by
log10(n). The ultimate complexity would be:I hope you've understood the concept properly...