Skip to content

Instantly share code, notes, and snippets.

@Enzime
Created August 27, 2015 07:48
Show Gist options
  • Save Enzime/dd195ccfe34e2493e39c to your computer and use it in GitHub Desktop.
Save Enzime/dd195ccfe34e2493e39c to your computer and use it in GitHub Desktop.
such Fraction class very std::pair
#include <iostream>
#include "Fraction.h"
Fraction::Fraction() { }
Fraction::Fraction(int a, int b) {
set(a, b);
}
Fraction::~Fraction() { }
void Fraction::set(int a, int b) {
int g = gcd(a, b);
m_a = a / g;
m_b = b / g;
if (m_b < 0) {
m_a = -m_a;
m_b = -m_b;
}
}
int Fraction::gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int Fraction::lcm(int a, int b) {
return a * b / gcd(a, b);
}
float Fraction::get() {
return (float) m_a / m_b;
}
void Fraction::get(int &a, int &b) {
a = m_a;
b = m_b;
}
Fraction& Fraction::operator-() {
m_a = -m_a;
return *this;
}
Fraction& Fraction::operator+=(Fraction& rhs) {
int a, b, l;
rhs.get(a, b);
l = lcm(b, m_b);
a *= l / b;
set((m_a * l / m_b) + a, l);
return *this;
}
Fraction& Fraction::operator-=(Fraction& rhs) {
*this += -rhs;
return *this;
}
Fraction& Fraction::operator*=(Fraction& rhs) {
int a, b;
rhs.get(a, b);
set(m_a * a, m_b * b);
return *this;
}
Fraction& Fraction::operator/=(Fraction& rhs) {
int a, b;
rhs.get(a, b);
rhs.set(b, a);
*this *= rhs;
return *this;
}
Fraction Fraction::operator+(Fraction& f) {
int a, b;
f.get(a, b);
Fraction frac(m_a, m_b);
frac += f;
return frac;
}
Fraction Fraction::operator-(Fraction& f) {
int a, b;
f.get(a, b);
Fraction frac(m_a, m_b);
frac -= f;
return frac;
}
Fraction Fraction::operator*(Fraction& f) {
int a, b;
f.get(a, b);
Fraction frac(m_a, m_b);
frac *= f;
return frac;
}
Fraction Fraction::operator/(Fraction& f) {
int a, b;
f.get(a, b);
Fraction frac(m_a, m_b);
frac /= f;
return frac;
}
Fraction& Fraction::operator=(int& a) {
m_a = a;
m_b = 1;
return *this;
}
#ifndef FRACTION_H
#define FRACTION_H
class Fraction {
private:
int m_a, m_b;
public:
Fraction();
Fraction(int a, int b);
~Fraction();
void set(int a, int b);
float get();
void get(int &a, int &b);
Fraction& operator-();
Fraction& operator+=(Fraction& rhs);
Fraction& operator-=(Fraction& rhs);
Fraction& operator*=(Fraction& rhs);
Fraction& operator/=(Fraction& rhs);
Fraction operator+(Fraction& f);
Fraction operator-(Fraction& f);
Fraction operator*(Fraction& f);
Fraction operator/(Fraction& f);
Fraction& operator=(int& a);
// Fraction& operator=(Fraction& f);
static int gcd(int a, int b);
static int lcm(int a, int b);
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment