11// Problem: Happy Number
22// Language: C++
3- // Problem: Happy Number (IEEEXtreme / LeetCode 202 style)
43// Description:
5- // A number is "happy" if repeatedly replacing the number by the sum of the
6- // squares of its digits eventually leads to 1. If the process enters a
7- // cycle that does not include 1, the number is not happy.
8- // Input/Output for this implementation:
9- // - This program reads a single positive integer n from stdin,
10- // computes whether n is a happy number, and prints "YES" if happy,
11- // otherwise prints "NO".
12- // Complexity:
13- // - Each transformation is O(d) where d = number of digits (<= log10 n).
14- // - For base-10 the sequence enters a cycle within limited bounds; overall
15- // expected time is small; space O(1) (Floyd cycle-detection) or O(k) if
16- // using a set where k is number of visited states.
4+ // A number is "happy" if repeatedly replacing the number by the sum
5+ // of the squares of its digits eventually leads to 1. If it enters
6+ // a cycle that does not include 1, the number is not happy.
7+ // Input: A single positive integer n
8+ // Output: "YES" if n is a happy number, otherwise "NO"
9+
10+ #include < iostream>
1711
18- #include < bits/stdc++.h>
1912using namespace std ;
2013
21- // compute sum of squares of digits of x
14+ // Function to compute the sum of squares of digits
2215long long sum_of_squares (long long x) {
2316 long long s = 0 ;
2417 while (x > 0 ) {
25- int d = x % 10 ;
26- s += 1LL * d * d;
18+ int d = static_cast < int >( x % 10 ) ;
19+ s += static_cast < long long >(d) * d;
2720 x /= 10 ;
2821 }
2922 return s;
3023}
3124
32- // Approach 1: Floyd's cycle detection (tortoise & hare).
33- // If the sequence reaches 1 -> happy. If cycle forms and doesn't include 1 -> not happy.
25+ // Floyd's cycle detection algorithm
3426bool isHappy (long long n) {
35- auto next = [](long long x){ return sum_of_squares (x); };
27+ auto next = [](long long x) {
28+ long long s = 0 ;
29+ while (x > 0 ) {
30+ int d = static_cast <int >(x % 10 );
31+ s += static_cast <long long >(d) * d;
32+ x /= 10 ;
33+ }
34+ return s;
35+ };
3636
3737 long long tortoise = n;
3838 long long hare = n;
39+
3940 while (true ) {
40- tortoise = next (tortoise); // move by 1
41- hare = next (next (hare)); // move by 2
41+ tortoise = next (tortoise);
42+ hare = next (next (hare));
4243 if (tortoise == 1 || hare == 1 ) return true ;
4344 if (tortoise == hare) return false ; // cycle detected
4445 }
@@ -50,6 +51,7 @@ int main() {
5051
5152 long long n;
5253 if (!(cin >> n)) return 0 ;
54+
5355 if (n <= 0 ) {
5456 cout << " NO\n " ;
5557 return 0 ;
@@ -60,14 +62,8 @@ int main() {
6062}
6163
6264/*
63- Sample:
64- Input:
65+ Sample Input:
656619
66- Output:
67+ Sample Output:
6768YES
68-
69- Explanation:
70- 19 -> 1^2 + 9^2 = 82
71- 82 -> 8^2 + 2^2 = 68
72- 68 -> 6^2 + 8^2 = 100
73- 100 -> 1^2 + 0 + 0 = 1 -> happy
69+ */
0 commit comments