Problem 1: (Filename: HappyNumber.java)
A happy number n is a positive integer defined by the following process:
• determine the sum of the squares of the digits of n
• repeat the process to the resulting sum of squares until the result equals 1
If n reaches this point, then n is a happy number. Otherwise, it will loop endlessly in a cycle which the calculated series of sum of squares does not include 1. Such a number is an unhappy number.
Illustration:
The number 7 is a happy number:
72 = 49
42 + 92 = 97
92 + 72 = 130
12 + 32 + 02 = 10
12 + 02 = 1
The number 5 is an unhappy number:
52 = 25 42 + 22 = 20
22 + 52 = 29 22 + 0 = 4
22 + 92 = 85 42 = 16
82 + 52 = 89 12 + 62 = 37
82 + 92 = 145 32 + 72 = 58
12 + 42 + 52 = 42 52 + 82 = 89
At this point, a cycle has occurred at the number 89.
Write a program that will read as input a nonzero integer n and determine whether it is a happy number or an unhappy number. Display the sum of squares that is calculated for each iteration. Since the generation of the sequence of numbers can lead to an infinite loop (for unhappy numbers), terminate the loop after 100 iterations (for as long as the calculated result is not equal to 1) and consider the number an unhappy number.
Algorithm:
• Input the value of n
• Declare a counter to keep track of the number of iterations so far and initialize it to 0.
• Declare a “working variable” num that will be manipulated in the body of the loop. The initial value of num will be the value of n.
• Declare a variable SumSquares, which will serve as the running sum of the squares of the digits of num.
• Determine SumSquares:
Set the value of SumSquares to 0.
Extract the digits of num following the approach in NumberPalindrome.
For each digit extracted, accumulate its square to SumSquares
Stop when there are no more digits to extract.
• Display the calculated sum of squares.
• Replace the value of num with SumSquares. Increment the counter.
• Repeat the process (from the fourth step). Terminate when the counter reaches 100 or when the sum of the squares is equal to 1.
• Output whether n is a happy or an unhappy number.
Sample Input and Output:
Input N: 7
49
97
130
10
1
7 is a happy number.

New Topic/Question
Reply




MultiQuote







|