-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhappyno.cpp
More file actions
47 lines (40 loc) · 1.19 KB
/
happyno.cpp
File metadata and controls
47 lines (40 loc) · 1.19 KB
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
#include <iostream>
#include <vector>
using namespace std;
// Helper function to calculate the sum of squares of digits of a number
int sumOfSquares(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
// Function to determine if a number is happy
bool isHappy(int n) {
vector<int> seen; // Vector to keep track of numbers we've already seen
while (n != 1) {
n = sumOfSquares(n); // Replace n with the sum of squares of its digits
// Check if the number has already been seen (cycle detection)
for (int i = 0; i < seen.size(); i++) {
if (seen[i] == n) {
return false; // If we encounter a number we've seen before, a cycle is detected
}
}
// Add the current number to the seen vector
seen.push_back(n);
}
return true; // The number became 1, so it's a happy number
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
if (isHappy(n)) {
cout << n << " is a happy number!" << endl;
} else {
cout << n << " is not a happy number!" << endl;
}
return 0;
}