Unhappy Numbers
Time limit1sMemory limit128 MB
Count numbers in [lo, hi] that never reach 1 under the digit-square-sum map; bounds go up to 1e18 so answers need digit DP over precomputed unhappy states.
- Level
Hard8 of 10
- Topics
- Math, Dynamic programming, Bit manipulation, Implementation
- Solved
- No attempts yet
Problem
Numbers have feelings too! For any positive integer, square each of its digits and add the squares together. Take that result and repeat the same process.
A number is Happy if, after repeating this process a finite number of times, the sum becomes . The number of iterations a happy number needs to reach is called its distance from happiness: the distance from happiness of is , and the distance from happiness of is , because , then , and finally .
A number is Unhappy if it is infinitely far from happiness: the process never reaches and instead gets stuck in a repeating loop.
Given the lower and upper bounds of a range of integers, determine how many Unhappy numbers lie in that range (inclusive).
Input
The input contains several test cases. Each test case is a single line with two positive integers and (), separated by a single space. The input ends with a line containing two zeros; this terminating line is not a test case and must not be processed.
Output
For each test case, print a single integer on its own line: the count of Unhappy numbers between and (inclusive). Print no extra spaces, and do not separate answers with blank lines.