-
Notifications
You must be signed in to change notification settings - Fork 0
/
4주차 실습-(2)
100 lines (89 loc) · 1.92 KB
/
4주차 실습-(2)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
###################
def double(n):
return n * 2
def halve(n):
return n // 2
###################
def mult1(m,n):
def loop(n,ans):
if n > 0:
return loop(n-1,ans+m)
else:
return ans
return loop(n,0)
def mult2(m,n):
ans = 0
while n > 0:
n -= 1
ans += m
else:
return ans
def fastmult1(m,n):
if n > 0:
if n % 2 == 0:
return fastmult1(double(m),halve(n))
else:
return m + fastmult1(m,n-1)
else:
return 0
def fastmult2(m,n):
def loop(m,n,ans):
if n > 0:
if n % 2 == 0:
return loop(double(m),halve(n),ans)
else:
return loop(m,n-1,ans+m)
else:
return ans
return loop(m,n,0)
def fastmult3(m,n):
ans = 0
while n > 0:
if n % 2 == 0:
m, n = double(m), halve(n)
else:
n -= 1
ans += m
return ans
def russianmult1(m,n):
def loop(m,n):
if n > 1:
if n % 2 != 0:
return m + russianmult1(double(m),halve(n))
else:
return loop(double(m),halve(n))
else: # n = 1;
return m
if n > 0:
return loop(m,n)
else:
return 0
def russianmult2(m,n):
def loop(m,n,ans):
if n > 1:
if n % 2 != 0:
return loop(double(m),halve(n),ans+m)
else:
return loop(double(m),halve(n),ans)
if n > 0:
return ans + m
else:
return 0
return loop(m,n,0)
def russianmult3(m,n):
ans = 0
while n > 1:
if n % 2 != 0:
m, n, ans = double(m), halve(n), ans+m
else:
m , n = double(m), halve(n)
if n > 0:
return ans + m
print(mult1(52,31))
print(mult2(31,37))
print(fastmult1(22,17))
print(fastmult2(61,29))
print(fastmult3(74,46))
print(russianmult1(41,25))
print(russianmult2(66,18))
print(russianmult3(29,31))