62 lines
1.1 KiB
C
62 lines
1.1 KiB
C
/* printer.c */
|
|
|
|
#include "computorv1.h"
|
|
|
|
bool is_nearly_equal(double num, int compare)
|
|
{
|
|
return is_nearly_equal_zero(num - compare);
|
|
}
|
|
|
|
bool is_nearly_equal_zero(double num)
|
|
{
|
|
if (num > DOUBLE_PRECISION)
|
|
return false;
|
|
if (num < -DOUBLE_PRECISION)
|
|
return false;
|
|
return true;
|
|
}
|
|
|
|
bool has_decimal_part(double num)
|
|
{
|
|
return (!is_nearly_equal(num, (int)num));
|
|
}
|
|
|
|
bool any_has_decimal_part(double *num, size_t len)
|
|
{
|
|
while (len > 0)
|
|
{
|
|
if (has_decimal_part(num[len - 1]))
|
|
return true;
|
|
len--;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// find GCD of two integers using euclidean algorithm
|
|
int gcd_int(int a, int b)
|
|
{
|
|
int tmp;
|
|
|
|
while (b != 0)
|
|
{
|
|
tmp = b;
|
|
b = a % b;
|
|
a = tmp;
|
|
}
|
|
return abs(a);
|
|
}
|
|
|
|
// returns the gcd, and modify arguments with new reduced values
|
|
int reduce_fraction(double *numerator, double *denominator)
|
|
{
|
|
int gcd;
|
|
|
|
if (any_has_decimal_part((double[]){*numerator, *denominator}, 2))
|
|
return 0;
|
|
|
|
gcd = gcd_int((int)*numerator, (int)*denominator);
|
|
*numerator /= gcd;
|
|
*denominator /= gcd;
|
|
|
|
return gcd;
|
|
} |