Problem overview
The function halvingSteps receives a positive integer n and returns how many times it must be divided by 2 until it becomes 1. Each division is an integer division, so the remainder is dropped: 9 divided by 2 is 4. Starting at 8, the path is 8, 4, 2, 1, which is 3 divisions. Starting at 9 it is 9, 4, 2, 1, also 3. If n is already 1, no division is needed and the answer is 0.
Approach
Repeat the division while n is bigger than 1 and count the repeats. Since the number of repeats isn't known up front, a loop with a condition fits. Go has no while, so it is written as a for with only a condition: for n > 1.
For n = 9, the values after each pass are:
| Pass | n afterwards | steps |
|---|---|---|
| 1 | 4 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 3 |
The loop stops as soon as n is 1, so the count holds every division made on the way.
Step by step
- Create
stepswith:=, starting at 0. No division has been made. - Loop while
n > 1. Ifnis 1 from the start, the loop doesn't run and the answer stays 0. - Divide:
n = n / 2. With two integers,/drops the remainder, so 9 becomes 4. This is also why the loop ends:ngets smaller on every pass. - Count it with
steps++, still inside the loop. - Return
stepsafter the loop.
The solution in Go
func halvingSteps(n int) int {
steps := 0
for n > 1 {
n = n / 2
steps++
}
return steps
}
Go details:
- Integer division. Because
nis anint,n / 2is a whole number. There is no fractional part to worry about. - The loop always ends. For
n > 1,n / 2is at least 1 and strictly smaller thann, sonreaches 1 and never drops to 0. That is why the condition can ben > 1. - Statements, not expressions.
steps++is a statement in Go, so it goes on its own line.
Complexity
Each pass halves n, so the loop runs about log base 2 of n times. For the largest input, 1000000000, it runs 29 times. The space is constant.
There is a shortcut for the same number, which the lesson doesn't ask for: the count equals the position of the highest set bit of n. In a file of your own, with math/bits imported, bits.Len(uint(n)) - 1 gives 3 for 8, 3 for 9, 0 for 1 and 29 for 1000000000. The loop shows the idea of repeated halving, and the shortcut is just a faster way to get the same answer.
Edge cases and common mistakes
- n = 1. The answer is 0, with no pass at all.
- Odd numbers. The remainder is dropped, so 9 goes to 4, not 4.5. The count stays correct because every pass still shrinks
n. - Powers of 2.
halvingSteps(8)is 3 because 8 is 2 multiplied by itself three times. For a power of 2 the answer is that exponent. - Using
n > 0. The loop then goes one pass too far, from 1 to 0, and the count is off by one. - Counting before checking. Starting
stepsat 1 gives the wrong answer forn = 1.
Testing
8gives 3.9gives 3.1gives 0.1000000000gives 29.
