Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Detect a happy number

Determine whether a number is happy using hashing or cycle detection.

Python practice14 minHashing & SetsIntermediateLast updated March 26, 2026

Problem statement

A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (happy) or it loops endlessly in a cycle that does not include 1 (unhappy). Given n, return True if n is happy, otherwise False.

Task

Implement the sequence transformation (sum of squares of digits) and detect cycles using a set or Floyd's algorithm.

Examples

Known happy

Input

n = 19

Output

True

19 -> 82 -> 68 -> 100 -> 1, so 19 is happy.

Input format

A positive integer n.

Output format

Boolean True if n is a happy number, otherwise False.

Constraints

1 <= n <= 2^31 - 1. Aim for O(log n) work per transformation and detect cycles efficiently.

Samples

Sample 1

Input

n = 7

Output

True

7 is a known happy number sequence leading to 1.