https://github.com/akkartik/mu/blob/master/406try-divide.mu
1
2
3 fn try-divide _nr: int, _dr: int -> _/eax: int {
4
5 var x/ecx: int <- copy 1
6 {
7
8
9 var tmp/edx: int <- copy _dr
10 tmp <- multiply x
11 compare tmp, _nr
12 break-if->
13 x <- shift-left 1
14 loop
15 }
16
17
18 var max/ecx: int <- copy x
19 var min/edx: int <- copy max
20 min <- shift-right 1
21
22 var i/eax: int <- copy min
23 {
24
25
26 var foo/ebx: int <- copy _dr
27 foo <- multiply i
28 compare foo, _nr
29 break-if->
30 i <- increment
31 loop
32 }
33 var result/eax: int <- copy i
34 result <- decrement
35
36
37
38 return result
39 }
40
41 fn test-try-divide-1 {
42 var result/eax: int <- try-divide 0, 2
43 check-ints-equal result, 0, "F - try-divide-1"
44 }
45
46 fn test-try-divide-2 {
47 var result/eax: int <- try-divide 1, 2
48 check-ints-equal result, 0, "F - try-divide-2"
49 }
50
51 fn test-try-divide-3 {
52 var result/eax: int <- try-divide 2, 2
53 check-ints-equal result, 1, "F - try-divide-3"
54 }
55
56 fn test-try-divide-4 {
57 var result/eax: int <- try-divide 4, 2
58 check-ints-equal result, 2, "F - try-divide-4"
59 }
60
61 fn test-try-divide-5 {
62 var result/eax: int <- try-divide 6, 2
63 check-ints-equal result, 3, "F - try-divide-5"
64 }
65
66 fn test-try-divide-6 {
67 var result/eax: int <- try-divide 9, 3
68 check-ints-equal result, 3, "F - try-divide-6"
69 }
70
71 fn test-try-divide-7 {
72 var result/eax: int <- try-divide 0xc, 4
73 check-ints-equal result, 3, "F - try-divide-7"
74 }
75
76 fn test-try-divide-8 {
77 var result/eax: int <- try-divide 0x1b, 3
78 check-ints-equal result, 9, "F - try-divide-8"
79 }
80
81 fn test-try-divide-9 {
82 var result/eax: int <- try-divide 0x1c, 3
83 check-ints-equal result, 9, "F - try-divide-9"
84 }
85
86
87 fn try-modulo nr: int, dr: int -> _/eax: int {
88 var _positive-nr/eax: int <- abs nr
89 var positive-nr/ecx: int <- copy _positive-nr
90 var result/eax: int <- try-divide positive-nr, dr
91 result <- multiply dr
92 result <- subtract positive-nr
93 result <- negate
94 return result
95 }
96
97 fn test-try-modulo-negative-nr {
98 var result/eax: int <- try-modulo -0xa, 7
99 check-ints-equal result, 3, "F - test-try-modulo-negative-nr"
100 }
101
102 fn abs n: int -> _/eax: int {
103 var result/eax: int <- copy n
104 {
105 compare n, 0
106 break-if->=
107 result <- negate
108 }
109 return result
110 }