28.5k views
5 votes
PLEASE HELP!! USE C++ PLEASE!!

Make a program that asks the user for an integer greater than zero (make sure that it’s greater than

zero), then checks whether or not that number is a happy number (explanation below). For this

program, you must use at least one recursive function to help determine whether or not the number is a

happy number.


To determine whether or not a number is a happy number, you take the sum of the squares of its digits.

Then you take that sum, and you find the sum of the squares of its digits. You repeat this process until

you end up at 1, which means it’s a happy number, or until you get stuck in a repeating cycle, which

means it’s not a happy number.

The repeating cycle is always 4→16→37→58→89→145→42→20→4


To summarize, find the sum of the squares of the digits until the sum is equal to either 1 (happy

number) or 4 (not happy number).


The first 10 happy numbers are: 1, 7, 10, 13, 19, 23, 28, 31, 32, and 44


Example:

73→49+9=58→25+64=89→64+81=145→1+16+25=42→16+4=20→4

73 makes it to 4, so 73 is not a happy number.

32→9+4=13→1+9=10→1+0=1

32 makes it to 1, so 32 is a happy number.

User Nasty
by
2.8k points

1 Answer

4 votes

#include <iostream>

#include <cassert>

#include <cstring>

#include <cmath>

std::string find_happy(int x) {

int sum = 0;

//Find the amount of digit of the current number.

int digit = int(log10(x) + 1);

for(int i=0;i<digit;i++) {

int d = x%10;

x/=10;

sum+=std::pow(d,2);

}

return (sum==4) ? "It's not happy number." : (sum==1) ? "It's happy number." : find_happy(sum);

}

int main(int argc, char* argv[]) {

std::cout << "Enter a number greater than zero: ";

int idx; std::cin>>idx;

assert(idx>0);

std::cout << find_happy(idx) << std::endl;

return 0;

}

PLEASE HELP!! USE C++ PLEASE!! Make a program that asks the user for an integer greater-example-1
User Mike Morearty
by
3.5k points