You are on page 1of 5

Hints for Assignment 1

A stub (function to be implemented)

Checking user option

You need a while loop to display all digits


Variable sum stores the sum of all digits

Arayabhata-Euclids algorithm: How to find


gcd(a,b), the greatest common divisor of a and b
based on a single observation: if a = b q + r, then
any divisor of a and b is also a divisor of r, and any divisor
of b and r is also a divisor of a, so gcd(a,b) = gcd(b,r)
Euclid algorithm: use the division algorithm repeatedly
To reduce the problem to one you can solve.
Example: gcd(55,35)
55 = 35*1 + 20
so gcd(55,35) = gcd(35,20)
35 = 20*1 + 15
so gcd(35,20) = gcd(20,15)
20 = 15*1 + 5
done gcd(55,35) = 5

Euclid Algorithm
To find the gcd of numbers A1 and A2 with A1 > A2 >= 0
a. If A2 = 0 then gcd = A1
b. If A2 > 0 then A1 = A2 q2 + A3 with A2>A3 >=0
c. Replace A1 by A2, A2 by A3 and go to step a.

This is exactly what we did in the previous example.

Example: gcd(120,85)
120 = 85*1 + 35
85 = 35*2 + 15
35 = 15*2 + 5
15 = 5*3 + 0

gcd = 5

(gcd is the last non-zero remainder)

Euclidean Algorithm.
Example
gcd(33,77):
Step

r=x%y

33

77

77

33

33

11

11

1
2
3

33 % 77
= 33
77 % 33
= 11
33 % 11
=0

Euclidean Algorithm.
Example
gcd(244,117):
Step

r=x%y

244

117

244 % 117 = 10

117

10

2
3
4

117 % 10 = 7
10 % 7 = 3
7%3=1

10
7
3

7
3
1

3 % 1=0

By definition 244 and 117 are relative prime.

Euclidean Algorithm
m,n

Euclidean
Algorithm

integer euclid(integer m, integer n)


x = m, y = n
while(y > 0)
or (y != 0)
r=x % y
x=y
y=r
return x

gcd(m,n)

You might also like