Knitting Pattern
InterviewTime limit1sMemory limit1024 MB
Given N loops and a pattern of P loops, find how many loops stay empty at the back when patterns are placed symmetrically around the front.
- Level
Easy3 of 10
- Topics
- Math, Implementation
- Solved
- No attempts yet
Problem
Jörmunrekur had some extra time, so he decided to look for a new hobby. After talking with some of his relatives, his grandparents lent him a book with knitting guides and knitting patterns.
He wanted to start with something big, so he decided to knit a sweater. He picked a pattern from the book and will repeat it around the circumference of the sweater. The pattern is centered, then repeated toward the back in either direction. He never wants less than a full pattern on the sweater. He will not place any pattern that makes the placements asymmetric. He needs to know how much empty space to leave at the back of the sweater to achieve this.
The empty space not covered by patterns must be a contiguous (possibly empty) section at the back of the sweater.
Input
The input contains two positive integers , the length of the sweater, and , the length of the pattern. They satisfy and have the same parity, since otherwise the pattern could never be perfectly centered.
Output
Print a single integer, the amount of empty space left on the back of the sweater.
Hint
In the first case the sweater is 13 loops in circumference. The centered pattern is placed at loops 6, 7 and 8. There is room for one more pattern on each side, at loops 3, 4, 5 and 9, 10, 11. There is not enough room for two more, and a single extra pattern on one side would make the layout asymmetric. So loops 1, 2, 12 and 13 stay empty, and the answer is 4.

Figure K.1: A possible pattern for the first case

Figure K.2: Applying the pattern to the full width for the first case
In the second case the sweater is 16 loops in circumference. The first pattern is placed at loops 7, 8, 9 and 10. Two more are placed at 3, 4, 5, 6 and 11, 12, 13, 14. That leaves loops 1, 2, 15 and 16, which exactly fit one more pattern centered at the back, so no empty space remains.

Figure K.3: A possible pattern for the second case

Figure K.4: Applying the pattern to the full width for the second case