293. Python Program to Find the Digital Root of a Number
MediumPhase 2 · Practice
Take it one step at a time. You know every tool here: two while loops, and % and // to take a number apart.
Overview
The digital root of a number is the single digit you get when you keep adding its digits. It is a good practice question, because it puts one loop inside another.
Problem Statement
Nadia's family plays a number game on long trips. Read a whole number n and find its digital root:
- Add up the digits of the number. For 9875, that is
9 + 8 + 7 + 5= 29. - If the result has two or more digits, add up its digits again: 29 gives 11, and 11 gives 2.
- Stop when only one digit is left. That digit is the digital root.
Print one line with the start number and every result after it, in order. Put -> between two numbers, with one space before it and one space after it. If n already has one digit, print just n.
Examples
Example 1. Input 9875 gives:
9875 -> 29 -> 11 -> 2
Why: 9 + 8 + 7 + 5 = 29. Then 2 + 9 = 11, and 1 + 1 = 2. The number 2 has one digit, so the chain stops.
Example 2. Input 7 gives:
7
Why: 7 already has one digit. There is nothing to add, so the line is just the number.
Input
One whole number n, 0 or more. It can have many digits. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line: the numbers of the chain, in order. Between two numbers there is a space, -> and a space. The tests try 8 different inputs.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.