livepython.net

295. Python Program to Check If a Number Is a Happy Number

MediumPhase 2 · Practice

This one takes a few steps, but you know every tool it uses: two while loops, % and // to take a number apart, and if.

Overview

Happy numbers are a classic number puzzle. You repeat the same step until you reach 1 or fall into a loop, so a while loop fits well.

Problem Statement

Leila's puzzle club checks which numbers are happy. Read a whole number n and repeat this step:

  • Replace the number with the sum of the squares of its digits. The square of a digit is the digit times itself. So 19 becomes 1 * 1 + 9 * 9, which is 82.
  • Stop when you reach 1. Then n is a happy number.
  • Stop when you reach 4. Then n is not a happy number.

Why 4? From 4, the numbers go 16, 37, 58, 89, 145, 42, 20 and then back to 4. They go round in a circle and never reach 1. Every number that is not happy falls into this circle, so it always meets 4.

Print two lines:

  • Line 1: the start number and every number after it, in order. Put -> between two numbers, with one space before it and one space after it. If n is 1 or 4, the line is just n.
  • Line 2: 19 is a happy number or 2 is not a happy number, with your number in place of 19 or 2.

Examples

Example 1. Input 19 gives:

19 -> 82 -> 68 -> 100 -> 1
19 is a happy number

Why: 1 * 1 + 9 * 9 = 82. Then 64 + 4 = 68, 36 + 64 = 100, and 1 + 0 + 0 = 1. The chain reaches 1, so 19 is happy.

Example 2. Input 2 gives:

2 -> 4
2 is not a happy number

Why: 2 * 2 = 4. The chain reaches 4, so 2 is not happy.

Input

One whole number n, 1 or more. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

Two lines, as shown above. The tests try 8 different inputs.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 11 · While Loops
solution.py
# write your code here

EXPECTED OUTPUT

119 -> 82 -> 68 -> 100 -> 1
219 is a happy number

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.