happy number Algorithm
The happy number algorithm is a mathematical process that involves taking a positive integer and replacing the number with the sum of the squares of its digits. The process is repeated until the resulting number either becomes 1 or loops endlessly in a cycle that does not include 1. If the number eventually reaches 1, it is considered a happy number; otherwise, it is classified as an unhappy number. The concept of happy numbers was first introduced by Reg Allenby, a British mathematician, in the 1970s.
To illustrate how the happy number algorithm works, let's take the number 19 as an example. First, we separate the digits of the number and square them: (1^2) + (9^2) = 1 + 81 = 82. Next, we repeat the process for the new number, 82: (8^2) + (2^2) = 64 + 4 = 68. Continuing the sequence, we have (6^2) + (8^2) = 36 + 64 = 100. Finally, (1^2) + (0^2) + (0^2) = 1. Since the number 1 has been reached, 19 is deemed a happy number. The happy number algorithm is often used in recreational mathematics and computer programming to explore number sequences and properties.
/* A happy number is a number whose sum of digits is calculated until the sum is a single digit,
and this sum turns out to be 1 */
// Copyright 2019 TheAlgorithms contributors
#include <iostream>
int main() {
int n, k, s = 0, d;
std::cout << "Enter a number:";
std::cin >> n;
s = 0;
k = n;
while (k > 9) {
while (k != 0) {
d = k % 10;
s += d;
k /= 10;
}
k = s;
s = 0;
}
if (k == 1)
std::cout << n << " is a happy number" << std::endl;
else
std::cout << n << " is not a happy number" << std::endl;
return 0;
}