-
Notifications
You must be signed in to change notification settings - Fork 0
/
Happy_Number.cpp
50 lines (41 loc) · 875 Bytes
/
Happy_Number.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <bits/stdc++.h>
using namespace std;
int sumDigitSquare(int n)
{
int sq = 0;
while (n) {
int digit = n % 10;
sq += digit * digit;
n = n / 10;
}
return sq;
}
bool isHappy(int n)
{
set<int> s;
s.insert(n);
while (1) {
// Number is Happy if we reach 1
if (n == 1)
return true;
// Replace n with sum of squares
// of digits
n = sumDigitSquare(n);
// If n is already visited, a cycle
// is formed, means not Happy
if (s.find(n) != s.end())
return false;
// Mark n as visited
s.insert(n);
}
return false;
}
int main()
{
int n = 23;
if (isHappy(n))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}