Out of Sorts
Time limit1sMemory limit512 MB
Given a linear congruential sequence of n distinct values, count how many of those values a binary search on the unsorted array would actually find.
- Level
Medium7 of 10
- Topics
- Divide and conquer, Binary search, Implementation, Math
- Solved
- No attempts yet
Problem
Ann Logan is fascinated with finite sequences of integers. She is particularly interested in sequences of the form where:
- ,
- , and are positive integer constants,
- is a non-negative integer constant, and
- all values are distinct.
For example, if , , , , and , the sequence is (, , and so on). She does not count the initial value as part of the sequence.
Ann wants to determine quickly, for any integer value, whether it appears in a finite sequence of this form. Given values of , and , she plans to follow this list of steps:
- Generate the sequence and store it in an array.
- Sort the array.
- Perform a binary search of the array for each integer of interest.
Ann's search algorithm is not the most efficient possible, but it is straightforward and understandable to anyone familiar with binary search. At each step, after computing the midpoint with , she first checks whether the value at position equals the search value . If not, she narrows the search according to whether is strictly less than or strictly greater than the value at position .
Unfortunately, Ann is absent-minded and lost her list of steps. She remembered the first and last step, but she forgot to sort the array before performing the binary search. Naturally, many values present in the unsorted array cannot be found by a binary search, though surprisingly some can. In the example above, both 4 and 7 can be found with Ann's binary search. How many values can be found for various sequences? Don't botch it up!
Input
The input consists of a line containing five integers , and (, , ). is the length of the sequence to be generated, and , and are the constants used to generate the sequence. All values in the generated sequence are guaranteed to be distinct.
Output
Output the number of sequence values that can be found with Ann's binary search, assuming she forgot to sort the sequence.