while Loops
Write halvings_until_below(value, limit) that repeatedly halves value and returns how many halvings it took to get strictly below .
halvings_until_below(100, 10) returns 4, because 100 goes to 50, 25, 12.5, 6.25, and 6.25 is the first value below 10.
If value is already below , return 0.
Examples
100 halved four times first drops below 10
- Input
- halvings_until_below(100, 10)
- Output
- 4
Already below the limit needs no halvings
- Input
- halvings_until_below(5, 10)
- Output
- 0
Exactly at the limit still needs one halving, since below is strict
- Input
- halvings_until_below(10, 10)
- Output
- 1
Hints
Hint 1
Work directly with the arguments value, and return the result rather than printing it.
Hint 2
Watch for this: used strictly greater condition.
Requirements
value: a positive number: a positive number
Return the number of halvings needed. 0 if value is already below limit.
Constraints
Standard library only, no imports required
Time limit: 200 ms, Memory: 64 MB
Where this shows up
3 employers weight this skill
2 frontier labs, 1 AI product company. Top match scores 80.
def halvings_until_below(value, limit):
"""
Count how many times you must halve value to get below limit.
Args:
value: a positive number
limit: a positive number
Returns:
The number of halvings needed. 0 if value is already below limit.
"""
# YOUR CODE HERE
pass