Problem
Ask
Submissions
Solution

Solution: Happy Number

Statement

Naive approach

The brute force approach is to repeatedly calculate the squared sum of digits of the input number and store the computed sum in a hash set. For every calculation, we check if the sum is already present in the set. If yes, we've detected a cycle and should return FALSE. Otherwise, we add it to our hash set and continue further. If our sum converges to 11, we've found a happy number.

While this approach works well for small numbers, we might have to perform several computations for larger numbers to get the required result. So, it might get infeasible for such cases. The time complexity is O(logn)O(\log n) because finding the next value requires processing each digit, which takes O(logn)O(\log n) time as the number of digits in nn is approximately logn\log n. Once the value drops below 243243, it can take, at most, 243243 more steps to terminate, which is a constant and, therefore, negligible. For numbers greater than ...

Problem
Ask
Submissions
Solution

Solution: Happy Number

Statement

Naive approach

The brute force approach is to repeatedly calculate the squared sum of digits of the input number and store the computed sum in a hash set. For every calculation, we check if the sum is already present in the set. If yes, we've detected a cycle and should return FALSE. Otherwise, we add it to our hash set and continue further. If our sum converges to 11, we've found a happy number.

While this approach works well for small numbers, we might have to perform several computations for larger numbers to get the required result. So, it might get infeasible for such cases. The time complexity is O(logn)O(\log n) because finding the next value requires processing each digit, which takes O(logn)O(\log n) time as the number of digits in nn is approximately logn\log n. Once the value drops below 243243, it can take, at most, 243243 more steps to terminate, which is a constant and, therefore, negligible. For numbers greater than ...