Have I been here before?
Follow a number sequence and use a set to notice when it loops. About 8 minutes.
Some processes go round in circles
Take a number, square each digit and add them up. 19 becomes 1 + 81 = 82, then 64 + 4 = 68, then 100, then 1. Some numbers reach 1 like that. Others circle forever through the same values: 4 goes round 16, 37, 58, 89, 145, 42, 20 and back to 4.
A plain loop can't tell "still going" from "stuck in a circle". You need a memory.
- seen
- {19}
Start at 19. Remember it in the seen set.
A set of places you've been
Remember every number you've seen in a set, like leaving breadcrumbs in a maze. If you ever land on a number that's already in the set, you're walking in a circle that doesn't include 1, so stop and answer no.
If you reach 1, the answer is yes.
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = sum(int(d) ** 2 for d in str(n))
return n == 1What comes after 82 in the digit-square process?
- A68
- B10
- C1
Show the answer
68. 8² + 2² = 64 + 4 = 68.
Happy number
Starting from n, repeatedly replace the number by the sum of the squares of its digits. Return true if this reaches 1, and false if it loops forever without reaching 1.
n = 19 → true
1 ≤ n ≤ 2,000,000,000