The Euclidean Algorithm | 프로그래밍의 벗 PivotOJ
PivotOJ

The Euclidean Algorithm

시간 제한: 1000ms메모리 제한: 128MB출처: NOI 1999BOJ 9924

문제

The famous Euclidean algorithm is found in Book VII of the Elements. The Elements was written in 300 B.C.~by the Greek mathematician Euclid. It is rumored that King Ptolemy, having looked through the Elements, hopefully asked Euclid if there were not a shorter way to geometry, to which Euclid severely answered: "In geometry there is no royal road!" Probably we should not blame the King for looking for short cuts, for there are thirteen books in the Elements\,! The books consist mainly of the mathematical knowledge amassed by Euclid, and possibly some discoveries of his own. The great achievement of Euclid is the beautifully systematic presentation of material as an organic whole. The Elements remained a standard work for over two thousand years. (see Episodes from the Early History of Mathematics, Asger Aaboe)

The modern Euclidean algorithm is often presented as

  1. Let AA and BB be integers with A>B0A > B \geq 0.
  2. If B=0B = 0, then the gcd is AA and the algorithm ends.
  3. Otherwise, find qq and rr such that \[ A = q B + r where 0 \leq r < B \] Note that we have 0r<B<A0 \leq r < B < A and gcd(A,B)=gcd(B,r)\gcd(A,B) = \gcd(B,r). Replace AA by BB, BB by rr. Go to Step 2.

But the original Euclidean algorithm uses subtraction instead of division. It is based on the observation that a common divisor of the positive integers AA, BB is also a common divisor of the integers min(A,B)\min(A,B), max(A,B)min(A,B)\max(A,B)-\min(A,B). Thus the gcd of two positive integers can be found as

  1. Let AA and BB be positive integers.
  2. If A=BA = B then the gcd is BB and the algorithm ends.
  3. Otherwise, replace AA by max(A,B)min(A,B)\max(A,B)-\min(A,B), BB by min(A,B)\min(A,B). Go to Step 2.

For example, given A=24,B=15A = 24, B = 15, the original Euclidean algorithm produces

  1. A=2415=9A = 24-15 = 9, B=15B = 15
  2. A=159=6A = 15-9 = 6, B=9B = 9
  3. A=96=3A = 9-6 = 3, B=6B = 6
  4. A=63=3A = 6-3 = 3, B=3B = 3

That is, before finding gcd(24,15)=3\gcd(24,15) = 3, the original Euclidean algorithm has to execute Step 3 four times.

입력

The input consists of one line containing two positive integers (each not larger than 32767) separated by one or more spaces.

출력

The output consists of one line containing one integer.

예제

예제 1

입력
24 15
출력
4
코드를 제출하려면 로그인하세요.