The Euclidean Algorithm
InterviewTime limit1sMemory limit128 MB
Count how many subtraction steps the original Euclidean algorithm needs to find the gcd of two integers up to 32767.
- Level
Easy2 of 10
- Topics
- Simulation, Math
- Solved
- No attempts yet
Problem
The famous Euclidean algorithm is found in Book VII of the Elements, written around 300 B.C. by the Greek mathematician Euclid. The story goes that King Ptolemy, having looked through the Elements, hopefully asked Euclid whether there was a shorter way to geometry, and Euclid severely answered: "In geometry there is no royal road!" We should probably not blame the King for looking for a short cut, because the Elements runs to thirteen books. The books consist mainly of the mathematical knowledge Euclid amassed, plus some discoveries of his own. Euclid's great achievement is the beautifully systematic presentation of the 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 usually presented like this.
- Let and be integers with .
- If , the gcd is and the algorithm ends.
- Otherwise find and with and . Here and . Replace by and by , then go to Step 2.
The original Euclidean algorithm uses subtraction instead of division. It rests on the observation that a common divisor of the positive integers and is also a common divisor of and . So the gcd of two positive integers can be found like this.
- Let and be positive integers.
- If , the gcd is and the algorithm ends.
- Otherwise replace by and by , then go to Step 2.
Starting from and , the original algorithm runs as follows.
- ,
- ,
- ,
- ,
That is, before reaching , it executes Step 3 four times.
Given two positive integers, count how many times the original Euclidean algorithm executes Step 3.
Input
The input consists of one line containing two positive integers separated by one or more spaces. Neither integer is larger than 32767.
Output
Print one line containing the number of times the original Euclidean algorithm executes Step 3.