4. In mathematics, a rational number is defined as a quotient of two where the d
ID: 3837117 • Letter: 4
Question
4. In mathematics, a rational number is defined as a quotient of two where the denominator is not equal to example, 1/ 6/1. and are all rational numbers as are fracti numerator and denominator are integers and the denominator is not e a. Declare a data structure that will contain a tional number b. Write functions that will add, subtract, multiply and divide rational bers. In all functions, pass in three parameters, each pointing a structure of the type you declared in part a. Use two of the parametert the operands, and the third for the result. c. write a function that takes a pointer to your data structure as a paramee and returns the greatest common divisor of the numerator and denomianExplanation / Answer
Hi,
Here is the code that I have implemented in C using structures-
#include <stdio.h>
#include <stdlib.h>
#define FMT "%lld"
typedef long long int fraction_int;
typedef struct { fraction_int num, den; } frac;
fraction_int gcd(fraction_int m, fraction_int n)
{
fraction_int t;
while (n) { t = n; n = m % n; m = t; }
return m;
}
frac frac_new(fraction_int num, fraction_int den)
{
frac a;
if (!den) {
printf("divide by zero: "FMT"/"FMT" ", num, den);
abort();
}
int g = gcd(num, den);
if (g) { num /= g; den /= g; }
else { num = 0; den = 1; }
if (den < 0) {
den = -den;
num = -num;
}
a.num = num; a.den = den;
return a;
}
#define BINOP(op, n, d) frac frac_##op(frac a, frac b) { return frac_new(n,d); }
BINOP(add, a.num * b.den + b.num * a.den, a.den * b.den);
BINOP(sub, a.num * b.den - b.num + a.den, a.den * b.den);
BINOP(mul, a.num * b.num, a.den * b.den);
BINOP(div, a.num * b.den, a.den * b.num);
int frac_cmp(frac a, frac b) {
int l = a.num * b.den, r = a.den * b.num;
return l < r ? -1 : l > r;
}
#define frac_cmp_int(a, b) frac_cmp(a, frac_new(b, 1))
int frtoi(frac a) { return a.den / a.num; }
double frtod(frac a) { return (double)a.den / a.num; }
int main()
{
int n, k;
frac sum, kf;
/*
for (n = 2; n < 1<<19; n++) {
sum = frac_new(1, n);
for (k = 2; k * k < n; k++) {
if (n % k) continue;
kf = frac_new(1, k);
sum = frac_add(sum, kf);
kf = frac_new(1, n / k);
sum = frac_add(sum, kf);
}
if (frac_cmp_int(sum, 1) == 0) printf("%d ", n);
}
*/
frac a,b;
a=frac_new(1,2);
b=frac_new(1,2);
sum=frac_add(a,b);
printf("%d ", sum);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.