← 返回 apple 的题目列表Happy number service (sum of squares of digits until reaches 1) + scaling
类型:online_judge
Coding: Happy Number Service
Implement a function/service: given a positive integer n, repeatedly:
Replace n with the sum of squares of its digits.
Repeat.
Return true if the process eventually reaches 1; return false if it falls into a cycle that never reaches 1.
I/O
Input: a positive integer n
Output: true/false
Constraints
Assume 64-bit integer input (e.g., 1 <= n <= 10^18).
Examples
Input: 19 → Output: true (19 → 82 → 68 → 100 → 1)
Input: 2 → Output: false
Follow-up (Scaling)
If this service must handle billions of requests per second, how would you optimize it?
Explain why values quickly collapse into a small range (e.g., < 1000).
How to exploit that with precomputation/caching (e.g., preload results for a bounded range).
Cache sizing, update strategy, and concurrency considerations.
Example
Input
19
Output
true