Lesson 3.3 · Write it
Halving steps
A whole programPython or Java6 tests, 3 of them hidden
On a phone? Put the lines in order instead
Write a program that reads a whole number and counts how many times it can be halved (using whole-number division) before it reaches 0.
- Read one number on a single line.
- Repeatedly divide the number by 2, keeping only the whole-number part, and count each division.
- Stop when the number reaches 0.
- Print
Steps:followed by the count. - If the number is already 0, the count is 0.
The number is always 0 or positive. Your program is run several times. Only what it prints is checked.
In Python, use // for whole-number division. In Java, / between two ints already drops the fraction.
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.
Examples
Your program is run 6 times: the 3 examples below, and 3 hidden ones that check the rules above. Only what it prints is checked.
8 halves to 4, 2, 1, 0 in four steps (rule 2)
You type
- typed: 8
It prints
Steps: 4
1 halves to 0 in one step (rule 2)
You type
- typed: 1
It prints
Steps: 1
already 0, no steps needed (rule 5)
You type
- typed: 0
It prints
Steps: 0