mooc-02 (2)
mooc-02 (2)
1
GCD Algorithm - Intuition
To find gcd of 8 and 6. Consider rods of length 8 and 6. Measure
the longer with the shorter. Take the remainder if any. Repeat the
process until the longer can be exactly measured as an integer
multiple of the shorter.
Remainder
Gcd(8, 6) = 2.
2
GCD Algorithm - Intuition
102
102 mod 21 = 18
21
21 mod 18 = 3
18
3
Euclid’s method for gcd
Euclid’s algorithm (step-by-step method for
calculating gcd) is based on the following
simple fact.
g= a%b Exchange(a,b)
a=b t= a
a%b is the remainder b=g a=b
when a is divided by b. b=t
Eg. 8%3 is 2 5
Variables and Assigning them
Input
Concept of
a, b variable: a name
for a box.
a,b,g are variables
Exchan
b≤a ge(a,b) that are names for
? NO integer boxes. b
a 5 3
YES
a 3 3 b
6
Sequential assignments
g = a%b;
Semi-colons give a
a = b; sequential order in
b = g; which to apply the
statements.
Variables are boxes
initially
After
After
a =b
g b= g
a %b
to which a name is
a b g
given.
10
6 4
6 ??
4
We have 3
variables: a, b, g.
This gives us three
boxes. Initially, a is
10, b is 6 and g is
undefined.
Run statements in
sequence. 7
Running the program
Input Program counter. At the next step
a, b to be executed. Initially at beginning.
8
Tracing the execution
Input
Now
Program
let us Counter
start running
is at the
thenext
flowchart.
step to
a, b Always
be runone box at a time.
3.
1.7.5.After
Test
Testinput
Test b==0?
b==0?step:
b==0? NO
YES
NO
Exchan
b≤a ge(a,b)
? NO 826 602 ??
02
YES
aaa bbb ggg
8. Print a
b== Print a Halt
0? 2
YES
NO 2.
4. Test
6. g=a%b;
b < a=b;
a? YES
b=g;
g= a%b
8
6
2 6
2
0 ??
2
0
a=b
b=g a b g
9
Multiple solutions and comparing them
Input
Multiple solutions are
a, b possible for the same
problem.
Exchan
b≤a ge(a,b)
Is the adjacent flowchart
? NO correct for gcd?
YES
Input
a, b
Exchan
b≤a ge(a,b)
? NO
YES