-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmurtoluku.c
122 lines (97 loc) · 1.93 KB
/
murtoluku.c
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <stdio.h>
#include <stdlib.h>
#include "murtoluku.h"
Murtoluku supistettuML(int os, int nim) {
int l, s, gcd; /* helpers, larger and smaller. Greatest Common Divisor */
Murtoluku res; /* actual result var. [if os or nim != 0] */
/* Make checks first */
if(os == 0 || nim == 0) {
Murtoluku zero;
zero.os = 0;
zero.nim = 0;
return zero;
/* is printed as 0 */
}
/* if nim is negative, multpl. both by -1 */
if(nim < 0) {
os *= -1;
nim *= -1;
}
/* ALG. starts */
l = max( abs(os), abs(nim) );
s = min( abs(os), abs(nim) );
while(l != s) {
l -= s;
if(l < s) {
int tmp;
tmp = l;
l = s;
s = tmp;
}
}
/* after l == s */
gcd = l; /* or s */
/* Part 2 */
res.os = os/gcd;
res.nim = nim/gcd;
return res;
}
Murtoluku lisaaML(Murtoluku a, Murtoluku b) {
int m1, m2;
m1 = a.nim;
m2 = b.nim;
a.os *= m2;
a.nim *= m2;
b.os *= m1;
b.nim *= m1;
/* */
return supistettuML(a.os+b.os, b.nim);
}
Murtoluku vahennaML(Murtoluku a, Murtoluku b) {
int m1, m2;
m1 = a.nim;
m2 = b.nim;
a.os *= m2;
a.nim *= m2;
b.os *= m1;
b.nim *= m1;
/* */
return supistettuML(a.os-b.os, b.nim);
}
Murtoluku kerroML(Murtoluku a, Murtoluku b) {
return supistettuML(
a.os*b.os,
a.nim*b.nim
);
}
/* Jakolasku on kertomista käänteisluvulla! */
Murtoluku jaaML(Murtoluku a, Murtoluku b) {
/* Swtich b's values */
int tmp;
tmp = b.os;
b.os = b.nim;
b.nim = tmp;
return kerroML(a,b);
}
void tulostaML(Murtoluku ml) {
if(ml.os != 0 && ml.nim != 1) {
printf("%d/%d", ml.os, ml.nim);
}
else if (ml.os == 0) {
printf("0");
}
/* nim == 0, print as int */
else if(ml.nim == 1) {
printf("%d", ml.os);
}
else {
printf("Error at printing");
exit(0);
}
}
int min(int a, int b) {
return (a <= b) ? (a) : (b);
}
int max(int a, int b) {
return (a >= b) ? (a) : (b);
}