The Program in C++Program to Find Happy Numbers between 1 to 1000 is given below:
#include <iostream>
#include <unordered_set>
using namespace std;
int sumOfSquaredDigits(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
bool isHappyNumber(int n) {
unordered_set<int> seen;
while (n != 1) {
n = sumOfSquaredDigits(n);
if (seen.count(n) > 0) {
return false;
}
seen.insert(n);
}
return true;
}
int main() {
cout << "Hello Codeauri Family, the Happy numbers between 1 and 1000 are: ";
for (int i = 1; i <= 1000; i++) {
if (isHappyNumber(i)) {
cout << i << " ";
}
}
cout << endl;
return 0;
}
Output:
Hello Codeauri Family, the Happy numbers between 1 and 1000 are: 1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 103 109 129 130 133 139 167 176 188 190 192 193 203 208 219 226 230 236 239 262 263 280 291 293 301 302 310 313 319 320 326 329 331 338 356 362 365 367 368 376 379 383 386 391 392 397 404 409 440 446 464 469 478 487 490 496 536 556 563 565 566 608 617 622 623 632 635 637 638 644 649 653 655 656 665 671 673 680 683 694 700 709 716 736 739 748 761 763 784 790 793 802 806 818 820 833 836 847 860 863 874 881 888 899 901 904 907 910 912 913 921 923 931 932 937 940 946 964 970 973 989 998 1000
Pro-Tips💡
This program implements the same sumOfSquaredDigits
and isHappyNumber
functions as in the previous program.
The main
function loops through all numbers between 1 and 1000 and calls the isHappyNumber
function for each number.
If the function returns true, the number is a happy number and is printed.
The output is a list of all happy numbers between 1 and 1000.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.