Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(Using C++) Problem 4: Happy numbers Problem 4: Happy numbers Write a program th

ID: 3812982 • Letter: #

Question

(Using C++)

Problem 4: Happy numbers

Problem 4: Happy numbers Write a program that prompts the user to input a positive integer number and check whether it is a happy number. A number is called happy number if you continue to add the square of its digits you end up with the digit 1. Use the fact that only 1 and 7 are 1-digit happy numbers If we take for example the happ y number 7: 7 81 49 130 12 32 02 10, 13 02 1 Sample input output nter a number 54 nter a number 973 4 is a not Happy number 73 is a Happy number

Explanation / Answer

#include<iostream.h>
#include<conio.h>

int compute(long);

int main()
{
long num;
int res;
clrscr();
cout<<" Input a number"<<endl;
cin>>num;
res=compute(num); // calling compute function
if(res==1) //checking if res equal to 1
cout<<num<<" is a Happy Number";
else
cout<<num<<" is a not a Happy Number ";
return 0;
}

int compute(long n) //function computes sum of the square of the digits upto n>10
{
long sum=0,r;
while(n>0) //loop iterates upto n>0
{
r=n%10; // stores the remainder i.e last digit
sum+=r*r; // square the remainder and add to sum
n=n/10; // new dividend
}

if(sum>=10) //checking sum >= 10
compute(sum); // recurrsively calling the function again
else
return sum; // return sum if it is single digit
}