-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdsa.py
69 lines (62 loc) · 1.49 KB
/
dsa.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def gcd(a,b): #function initilization
facta=[];
factb=[];
for i in range(1,a+1): #iteration number 1 and finding divisors
if a%i==0:
facta.append(i);
else:
continue;
for j in range(1,b+1): #iteration number 2 and finding divisors
if b%j==0:
factb.append(j);
else:
continue;
print(facta);
print(factb);
common=[];
for i in range(len(facta)): #finding common terms
for j in range(len(factb)):
if facta[i]==factb[j]:
common.append(facta[i])
print(common);
print(common[-1]) #pickint the max term
gcd(8,40)
#one scan model still can be improved
def gcd2(a,b):
cf=[];
for i in range(1,min(a,b)+1):
if a%i==0 and b%i==0:
cf.append(i);
else:
continue;
print(cf[-1]);
gcd2(8,40)
#not storing list
def gcd3(a,b):
for i in range(1,min(a,b)+1):
if a%i==0 and b%i==0:
mrcf=i;
else:
continue;
print(mrcf);
gcd3(6,14)
#scanning backward
def gcd4(a,b):
for i in range(min(a,b),1,-1):
if a%i==0 and b%i==0:
mrcf=i;
break;
else:
continue;
print(mrcf)
gcd4(6,14)
#Euclid algorithm
def gcd5(a,b):
if b>a:
a,b=b,a;
if a%b==0:
print(b);
else:
r=a%b;
return(gcd5(b,r))
gcd5(6,14)