-
Notifications
You must be signed in to change notification settings - Fork 0
/
fracs.c
76 lines (52 loc) · 1.38 KB
/
fracs.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
/*
fracs.c
Methods for working with structures meant to represent mathematical fractions.
Copyright (c) 2018 andynines
MIT License
*/
// Includes
#include <stdlib.h>
#include "allocs.h"
#include "fracs.h"
// Functions for working with fractions
static int gcd(int a, int b) {
// Ruthlessly stolen from Wikipedia
int temp;
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
Fraction* createFrac(int num, int denom) {
/*
Given a numerator and denominator, allocate the space to store these ints in
a fraction "object" for further calculations. Return a pointer to the new
structure.
*/
Fraction* newFracPtr;
newFracPtr = (Fraction*) safeMalloc(sizeof(Fraction));
newFracPtr->num = num;
newFracPtr->denom = denom;
return newFracPtr;
}
void simplifyFrac(Fraction* fracPtr) {
/*
Given a pointer to a fraction structure, reduce its numerator and
denominator down to their simplest form.
*/
int currentGcd;
int gcd(int a, int b);
while ((currentGcd = gcd(fracPtr->num, fracPtr->denom)) > 1) {
fracPtr->num /= currentGcd;
fracPtr->denom /= currentGcd;
}
}
void destroyFrac(Fraction* fracPtr) {
/*
Wrap the standard deallocation method for completeness. Free the fraction
structure pointed to by the argument.
*/
free(fracPtr);
}