File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // Problem: Happy Number
2+ // Language: C++
3+ // Description:
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>
11+
12+ using namespace std ;
13+
14+ // Function to compute the sum of squares of digits
15+ long long sum_of_squares (long long x) {
16+ long long s = 0 ;
17+ while (x > 0 ) {
18+ int d = static_cast <int >(x % 10 );
19+ s += static_cast <long long >(d) * d;
20+ x /= 10 ;
21+ }
22+ return s;
23+ }
24+
25+ // Floyd's cycle detection algorithm
26+ bool isHappy (long long n) {
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+ };
36+
37+ long long tortoise = n;
38+ long long hare = n;
39+
40+ while (true ) {
41+ tortoise = next (tortoise);
42+ hare = next (next (hare));
43+ if (tortoise == 1 || hare == 1 ) return true ;
44+ if (tortoise == hare) return false ; // cycle detected
45+ }
46+ }
47+
48+ int main () {
49+ ios::sync_with_stdio (false );
50+ cin.tie (nullptr );
51+
52+ long long n;
53+ if (!(cin >> n)) return 0 ;
54+
55+ if (n <= 0 ) {
56+ cout << " NO\n " ;
57+ return 0 ;
58+ }
59+
60+ cout << (isHappy (n) ? " YES\n " : " NO\n " );
61+ return 0 ;
62+ }
63+
64+ /*
65+ Sample Input:
66+ 19
67+ Sample Output:
68+ YES
69+ */
You can’t perform that action at this time.
0 commit comments