Square Bounce
Time limit7sMemory limit1024 MB
A ray starts at (-1,0) inside a unit square, bounces n times off the sides at equal angles, and you report the rational coordinates of the n-th hit point in lowest terms.
- Level
Medium6 of 10
- Topics
- Math, Geometry, Number theory, Simulation
- Solved
- No attempts yet
Problem
Given a square in the plane with corners at , , and , we fire a ray from point into the interior of the square on a path with a given slope. The ray bounces off of the sides of the square with an angle of reflection which is the same as the angle of incidence to the side at the point of intersection.

After a number of bounces, the ray intersects one of the square's sides again at some point which has rational coordinates. Find those rational coordinates in reduced form.
Input
The single line of input contains three integers , and (, ), where the slope of the ray's initial path is , and there are bounces. Note that and are relatively prime. The slope will be chosen so that the ray never bounces at a corner of the square.
Output
Output a single line with four space-separated integers , , and , where is the final point where the ray hits a side of the square, and are in reduced form, and the denominators ( and ) are positive. If one of the coordinates has value , output it as 0 1.
Hint
The following is a picture of the first sample:
