A Flea on a Chessboard


An infinite chessboard is obtained by extending a finite chessboard to the right and up infinitely. Each square of the chessboard is either black or white with the side length of $S$ millimeters. The leftmost bottom square of the chessboard is black. A flea is positioned on the chessboard at the point $(x, y)$ (given in millimeters) and makes jumps by jumping $dx$ millimeters to the right and $dy$ millimeters up. That is, a flea at position $(x, y)$ after one jump lands at position $(x+dx, y+dy)$.

Given the starting position of the flea on the board your task is to find out after how many jumps the flea will reach a white square. If the flea lands on a boundary between two squares then it does not count as landing on the white square. Note that it is possible that the flea never reaches a white square.


Input consists of multiple test cases, at most $1024$. Each test case consists of one line of input containing five integers $S$, $x$, $y$, $dx$, and $dy$ ($1 \le S \le 1000$, $0 \le x, y \le 10^6$, $1 \le dx, dy \le 10^6$). An input line containing five zeroes follows the last test case.


For each test case print one line of output in the format shown in the sample.

Sample Input 1 Sample Output 1
10 2 3 3 2
100 49 73 214 38
25 0 0 5 25
407 1270 1323 1 1
18 72 6 18 6
407 1270 1170 100 114
0 0 0 0 0
After 3 jumps the flea lands at (11, 9).
After 1 jumps the flea lands at (263, 111).
The flea cannot escape from black squares.
After 306 jumps the flea lands at (1576, 1629).
The flea cannot escape from black squares.
After 0 jumps the flea lands at (1270, 1170).
CPU Time limit 1 second
Memory limit 1024 MB
Statistics Show
Piotr Rudnicki
Source Waterloo Programming Contest 2004-01-31
License Creative Commons License (cc by)

Please log in to submit a solution to this problem

Log in