Course navigation & on this pageLecture 03 · CS-702
Euclid’s algorithm & recursion
Compute a greatest common divisor through a shrinking sequence of remainders.
Beginner~35 min guideSource-based learning
What you’ll understand
Explain why the GCD is preserved by taking a remainder.
Trace both supplied Euclidean implementations.
Identify the base case and the cost of recursive calls.
Before you begin: Integer division and remainder · Java methods
Expanded study guide
The greatest common divisor
The greatest common divisor of two nonnegative integers, not both zero, is the largest positive integer dividing both. For 48 and 18, the common divisors are 1, 2, 3 and 6; the greatest is 6.
The source introduces Euclid’s method for efficiently computing this value. The implementation contains both a recursive gcd and an iterative gcd2, allowing the same mathematical idea to be studied in two forms.
Why remainders preserve the answer
Write p = kq + r, where r is p modulo q. Every divisor of p and q also divides r = p − kq. Conversely, a divisor of q and r divides p = kq + r. Therefore the two pairs have exactly the same common divisors.
Replacing (p, q) by (q, r) preserves the answer and shrinks the second argument when q is positive. When q is zero, p is the answer.
gcd(p,q)=gcd(q,pmodq),gcd(p,0)=p
A complete dry run: gcd(48, 18)
48 = 2 × 18 + 12, so replace (48, 18) with (18, 12). Next, 18 = 1 × 12 + 6, giving (12, 6). Finally, 12 = 2 × 6 + 0, giving (6, 0). The zero second argument triggers the base case, returning 6.
Call 1: gcd(48, 18) → gcd(18, 12).
Call 2: gcd(18, 12) → gcd(12, 6).
Call 3: gcd(12, 6) → gcd(6, 0).
Call 4: return 6; the suspended calls return the same value.
Remainder trace
gcd(48, 18)
Call
p
q
p mod q
1
48
18
12
Replace (48, 18) with (18, 12).
The source examples: 12, 10 and 270, 192
The original lecture first lists divisors. For 30, 36 and 24, the common divisors are 1, 2, 3 and 6, so their GCD is 6. For 13 and 48, only 1 is common, so they are coprime.
For gcd(12, 10), use 12 = 10 × 1 + 2, then 10 = 2 × 5 + 0. The result is 2. For gcd(270, 192), the remainders are 78, 36, 6 and 0, giving a GCD of 6. These preserve the worked inputs from the source pages.
The source also explains the subtraction form: gcd(A, B) = gcd(B, A − B). Repeated subtraction gives gcd(A − QB, B), which is the remainder step when Q is the quotient. The proof works in both directions: a common divisor of A and B divides their difference, and a common divisor of B and A − B divides their sum A.
Reading the original code
In gcd, if (q == 0) return p is the stopping condition. The recursive call passes q as the next first argument and p % q as the next second argument. No work is required after that call returns.
In gcd2, temp preserves the old q before q is overwritten. Updating p = temp completes the state transition. Omitting the temporary value would mix the old and new states.
The original comment warns that negative inputs may produce a negative result. This code is preserved as supplied. For the standard positive GCD interpretation, use nonnegative inputs. The code returns 0 for (0, 0), while the largest-positive-divisor definition does not define that case.
How fast does the problem shrink?
For positive inputs, the number of remainder steps is O(log min(p, q)); consecutive Fibonacci numbers produce the slowest Euclidean reduction pattern. This counts arithmetic operations, assuming each integer remainder is a unit-cost operation.
The iterative version uses O(1) extra variables. The recursive version uses O(log min(p, q)) call frames in the worst case. With arbitrary-precision integers, arithmetic operations themselves have a size-dependent cost.
Remember for revision
Explain both preservation and progress: the GCD does not change, and a positive remainder is smaller than its divisor. State the input assumptions when discussing correctness or complexity.
Original implementations
Read the complete original code and its documentation. Core algorithm pages add a walkthrough, complexity discussion and a worked example.
Supplementary practice. Try each question before opening the answer.
Trace gcd(1071, 462).
1071 mod 462 = 147; 462 mod 147 = 21; 147 mod 21 = 0. The GCD is 21.
Why must gcd2 save q in temp?
The next p must be the previous q. Once q is replaced with the remainder, that old value would otherwise be lost.
Original course material
Complete lecture source
Every source page is preserved below. Open a page to read its text and inspect the original diagram, formula or example. Expanded explanations above are supplementary.
Page 01 · Euclidean AlgorithmsOriginal page 1 · Open the image for full detail.
Euclidean Algorithms
In mathematics, the Euclidean algorithm or Euclid's
algorithm, is an efficient method for computing the greatest
common divisor (GCD) of two integers (numbers), the largest
number that divides them both without a remainder.
• Euclid - Laws of nature are just the mathematical
thoughts of God.
• Ancient Greek mathematician Euclid in Alexandria,
Ptolemaic Egypt c. 300 BC.
• Father of Geometry
Page 02 · Visual explanation / original slideOriginal page 2 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
EXAMPLE
Find the greatest common divisor of 30, 36, and 24.
The divisors of each number are given by
30 :1, 2, 3, 5, 6, 10, 15, 30
36 :1, 2, 3, 4, 6, 9, 12, 18, 36
24 :1, 2, 4, 6, 12, 24
The largest number that appears on every list is 6, so this is the greatest common divisor:
gcd(30, 36, 24) = 6.
Page 03 · Visual explanation / original slideOriginal page 3 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Page 04 · Visual explanation / original slideOriginal page 4 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Page 05 · Visual explanation / original slideOriginal page 5 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Page 06 · Visual explanation / original slideOriginal page 6 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Page 07 · Visual explanation / original slideOriginal page 7 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Page 08 · Visual explanation / original slideOriginal page 8 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Page 09 · Visual explanation / original slideOriginal page 9 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Page 10 · Visual explanation / original slideOriginal page 10 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Page 11 · Visual explanation / original slideOriginal page 11 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
A=36, B=6
·B#0
.Uselongdivisiontofindthat36/6=6witharemainderof0.Wecan
write this as:
36=6*6+0
Find GCD(6,0), since GCD(36,6)=GCD(6,0)
Page 12 · Visual explanation / original slideOriginal page 12 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Page 13 · Visual explanation / original slideOriginal page 13 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Understanding the Euclidean Algorithm
IfweexaminetheEuclideanAlgorithmwecanseethatitmakesuseofthe
following properties:
· GCD(A,O) = A
GCD(O,B) = B
·If A=B.Q+Rand B+O then GCD(A,B) =GCD(B,R) whereQis an integer,
RisanintegerbetweenOandB-1
Thefirsttwopropertieslet usfindtheGCDifeithernumberisO.Thethird
propertylets us takea larger,moredifficulttosolveproblem,and reduceitto
asmaller,easiertosolveproblem
Page 14 · Visual explanation / original slideOriginal page 14 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
TheEuclideanAlgorithmmakesuseofthesepropertiesbyrapidlyreducingthe
problem into easier and easier problems, using the third property, until it is
easilysolvedbyusingone ofthefirsttwoproperties.
Wecanunderstandwhythesepropertiesworkbyprovingthem.
WecanprovethatGCD(A,O)=Aisasfollows:
.The largest integer that can evenlydivideA isA.
·All integers evenly divide O, since for any integer, C, we can write C .O =0.
SowecanconcludethatAmustevenlydivideO.
.ThegreatestnumberthatdividesbothAandOisA.
TheproofforGCD(o,B)=Bissimilar.(Sameproof,butwereplaceAwithB)
Page 15 · Visual explanation / original slideOriginal page 15 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
To provethat GCD(A,B)=GCD(B,R) we first need to show that
GCD(A,B)=GCD(B,A-B)
AND
THUS
GCD(A,B)
GCD(B,C)= GCD(B, A-B)
SupposewehavethreeintegersA,BandCsuchthatA-B=C.
Page 16 · Visual explanation / original slideOriginal page 16 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
ProofthattheGCD(A,B)evenlydividesC
The GCD(A,B), by definition, evenly divides A. As a result, A must be some
multiple of GCD(A,B). i.e. X.GCD(A,B)=A where X is some integer
The GCD(A,B), bydefinition,evenly divides B.As a result, B must be some
multiple of GCD(A,B). i.e. Y.GCD(A,B)=B where Y is some integer
A-B=C gives us:
·X.GCD(A,B) - Y.GCD(A,B) = C
· (X - Y)·GCD(A,B) = C
SowecanseethatGCD(A,B)evenlydividesC
Page 17 · Visual explanation / original slideOriginal page 17 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Page 18 · Visual explanation / original slideOriginal page 18 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
ProofthattheGCD(B,C)evenlydividesA
The GCD(B,C), by definition, evenly divides B. As a result, B must be some
multiple of GCD(B,C). i.e. M.GCD(B,C)=B where M is some integer
TheGCD(B,C),bydefinition,evenlydividesC.Asaresult,Cmustbesome
multiple of GCD(B,C). i.e. N.GCD(B,C)=C where N is some integer
A-B=C gives us:
·B+C=A
M·GCD(B,C) + N·GCD(B,C) = A
· (M + N)-GCD(B,C) = A
SowecanseethatGCD(B,C)evenlydividesA.
Page 19 · Visual explanation / original slideOriginal page 19 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Page 20 · Visual explanation / original slideOriginal page 20 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Proof that GCD(A,B)=GCD(A,A-B)
·GCD(A,B) by definition, evenly divides B
.We proved that GCD(A,B) evenly divides C.
·SincetheGCD(A,B)dividesbothBandC evenly it isacommondivisorof
B and C.
GCD(A,B) must be less than or equal to, GCD(B,C), because GCD(B,C) is the
"greatest"commondivisorofBandC.
.GCD(B,C) by definition, evenly divides B.
. We proved that GCD(B,C) evenly divides A.
·SincetheGCD(B,C)dividesbothAandBevenlyitisacommondivisorof
A and B.
GCD(B,C)mustbe lessthan orequalto,GCD(A,B),becauseGCD(A,B)isthe
“greatest"common divisor of Aand B.
Page 21 · Visual explanation / original slideOriginal page 21 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Given that GCD(A,B)≤GCD(B,C)and GCD(B,C)≤GCD(A,B) we can conclude
that:
GCD(A,B)=GCD(B,C)
Whichisequivalentto:
GCD(A,B)=GCD(B,A-B)
Page 22 · Visual explanation / original slideOriginal page 22 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Anillustrationofthisproofisshownintherightportionofthefigurebelow.
AND
THUS
GCD(A,B)
GCD(B.C)=GCD(B.A-B)
Page 23 · Visual explanation / original slideOriginal page 23 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
Proof that GCD(A,B)= GCD(B,R)
We proved that GCD(A,B)=GCD(B,A-B)
The order of thetermsdoes not matterso we can say GCD(A,B)=GCD(A-B,B)
We can repeatedly apply GCD(A,B)=GCD(A-B,B) to obtain:
GCD(A,B)=GCD(A-B,B)=GCD(A-2B,B)=GCD(A-3B,B)=...=GCD(A-Q·B,B)
But A= B.Q + R so A-Q·B=R
Thus GCD(A,B)=GCD(R,B)
The order of terms does not matter, thus:
GCD(A,B)=GCD(B,R)
Page 24 · Visual explanation / original slideOriginal page 24 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
publicclassEuclid(
//recursive implementation
public static int gcd(int p, int q)(
if(q==o)return p;
elsereturn gcd(q,p %q);
//non-recursive implementation
public static int gcd2(int p,int q)(
while (q != 0) {
int
temp=
q;
q = p % q;
p=
temp;
return
p;
Page 25 · Visual explanation / original slideOriginal page 25 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
//main method
public static void main(String[ args)(
int
Integer.parseInt(args[o]);
int
Integer.parseInt(args[i]);
int
=gcd(p,q);//resursion
intd2=gcd2(p,q);//whileloop
System.out.println("gcd("+p
:(P +
System.out.println("gcd(+
+ d2) ;
Page 26 · Visual explanation / original slideOriginal page 26 · Open the image for full detail.Searchable transcription (OCR; verify formulas against the image)
public class Euclid(
//recursive implementation
public static int gcd(int p,int q)(
if (q==0)return p;
elsereturngcd(q,p%q);
//non-recursiveimplementation
public static int gcd2(intp,intq)(
while(q!=0)(
int temp=q;
q = p % q;
p = temp;
return p;
// main method
public static void main(string[]args)(
intp =Integer.parseInt(args[o]);
int q = Integer.parseInt(args[1]);
int d=gcd(p,q);//resursion
intd2=gcd2(p,q);//whileloop
System.out.printIn("gcd("
d);
System.out.println("gcd("
d2);