Algo-Sim › Math & Geometry
Happy Number
Easy · Math & Geometry · step through it in Java, Python and C++ on your own input
Repeatedly sum the squares of the digits; detect the loop with Floyd’s slow and fast pointers, using O(1) memory instead of a set.
Problem
A number is happy if repeatedly replacing it by the sum of the squares of its digits eventually reaches 1. Otherwise the process loops forever in a cycle that does not include 1. Return true if n is happy.
Constraints
- 1 ≤ n ≤ 2³¹ − 1
Edge cases to test
- n = 1
- A number that falls into the 4 → 16 → 37 … cycle
- Large n (shrinks fast after one step)
Follow-up questions
- Why must it end in a cycle or at 1?
- After one step any number below 10¹⁰ becomes at most 810, so the sequence lives in a finite set and must repeat.
- Set or Floyd’s cycle detection?
- A set is simpler but uses memory; Floyd’s slow and fast pointers use O(1) space with the same O(log n) steps per move.
Solution
Java
public boolean isHappy(int n) {
int slow = n, fast = next(n);
while (fast != 1 && slow != fast) {
slow = next(slow);
fast = next(next(fast));
}
return fast == 1;
}
private int next(int n) {
int sum = 0;
while (n > 0) {
int d = n % 10;
sum += d * d;
n /= 10;
}
return sum;
}Python
def is_happy(n):
slow, fast = n, next_number(n)
while fast != 1 and slow != fast:
slow = next_number(slow)
fast = next_number(next_number(fast))
return fast == 1
def next_number(n):
total = 0
while n > 0:
n, d = divmod(n, 10)
total += d * d
return totalC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isHappy(int n) {
int slow = n, fast = next(n);
while (fast != 1 && slow != fast) {
slow = next(slow);
fast = next(next(fast));
}
return fast == 1;
}
int next(int n) {
int sum = 0;
while (n > 0) {
int d = n % 10;
sum += d * d;
n /= 10;
}
return sum;
}
};
More Math & Geometry problems
- Plus One (Easy)
- GCD and LCM (Euclid) (Easy)
- Count Primes (Sieve of Eratosthenes) (Medium)
- Pow(x, n) (Medium)
- Count Good Numbers (mod 1e9+7) (Medium)
- Multiply Strings (Medium)
- Reverse Integer (Medium)
- String to Integer (atoi) (Medium)
- Detect Squares (Medium)
- Random Pick with Weight (Medium)
- Shuffle an Array (Medium)
- Linked List Random Node (Medium)
- Pascal's Triangle (Easy)
- nCr mod p (Medium)
- Max Points on a Line (Hard)