The Binary Search Efficiency Doubter
Time limit1sMemory limit256 MB
Given a list length n, compute the total number of binary search loop iterations spent finding every element.
- Level
Medium5 of 10
- Topics
- Math, Binary search, Recursion
- Solved
- No attempts yet
Problem
Binary search is a classic algorithm in computer science. This problem defines binary search by the following pseudocode.
Search the array a, over a[0] through a[n-1], for the value x.
Assume the values in a are in strictly increasing order.
Low = 0
High = n - 1
While Low <= High
Mid = (Low + High) / 2 [integer division truncates]
If a[Mid] = x then return FOUND
If a[Mid] < x then Low = Mid + 1
If a[Mid] > x then High = Mid - 1
If the while loop ends, return NOT_FOUND
Professors teach that the algorithm is efficient, that the loop runs about times in the worst case, and that the average is a little better than that. A student who is not convinced builds lists of several sizes, searches for every value in the list, and counts how many times the loop runs. In the list below, the number of loop iterations spent finding each value is written under that value.
The total loop count for this list is 17.
As long as the list is sorted and all the values are different, every list of length 7 has a total loop count of 17. The length of the list determines the total loop count.
Given the length of the list, compute the total loop count. The answer for every case in the input fits in a signed 64-bit integer.
Input
The input holds several cases. Each case is a single positive integer , the length of the list. , and there are at most 100 cases. Any whitespace separates the cases. Read until end of file.
Output
For each case, print the total loop count for finding all the values in a list of length . Follow this format exactly: "Case", one space, the case number, a colon, one space, and the answer for that case. Do not print trailing spaces.