Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Happy Numbers

Check happy numbers by repeating digit-square sums in Python. Students track visited states and stop either at one or when a repeated state proves a cycle.

AdvancedPhase 6 - Category 1: Number LogicExample 8 of 10
happy-numbers.py
1def sum_square_digits(n):
2 total = 0
3 while n > 0:
4 digit = n % 10
5 total += digit * digit
6 n //= 10
7 return total
8
9def is_happy(n):
10 seen = set()
11 while n != 1 and n not in seen:
12 seen.add(n)
13 n = sum_square_digits(n)
14 return n == 1
15
16# Test
17num = int(input("Enter a number: "))
18if is_happy(num):
19 print("Happy number")
20else:
21 print("Not a happy number")

Output

Enter a number: 19
Happy number

In this one

  • Iterate a number transform
  • Detect a repeated state
  • Distinguish cycles from success

How it works

  1. 1

    Start a fresh seen set.

  2. 2

    Record n and replace it with its digit-square sum.

  3. 3

    Stop on one or a previously seen state.

Edge cases

Why store seen values?

Why store seen values?

To stop when the process repeats instead of reaching one.

Is zero happy here?

Is zero happy here?

No. It repeats zero without reaching one.

What's going on

sum_square_digits replaces a positive integer by the total of its squared digits. is_happy repeats that transformation.

seen records each state before the next step. Reaching one succeeds; revisiting any earlier state prevents an infinite cycle and fails. For nineteen, the path reaches one. Zero stays in a cycle at zero, while negative input falls to zero under this helper's loop.

Why store seen values? To stop when the process repeats instead of reaching one.

Is zero happy here? No. It repeats zero without reaching one.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What signals success?

Pick an answer to check it.

Question 2

Why store seen values?

Pick an answer to check it.

Questions people ask

Why store seen values?

To stop when the process repeats instead of reaching one.

Is zero happy here?

No. It repeats zero without reaching one.

What signals success?

n == 1.