Skip to content

Instantly share code, notes, and snippets.

@ada10fl2
Last active August 29, 2015 13:56
Show Gist options
  • Save ada10fl2/9259947 to your computer and use it in GitHub Desktop.
Save ada10fl2/9259947 to your computer and use it in GitHub Desktop.
A fast Rational i c++, using Binary GCD ( __builtin_ctz )
#include <iostream>
#include <algorithm>
using namespace std;
class Rational {
private:
size_t p;
size_t q;
size_t ctz(size_t x){
return __builtin_ctz(x);
}
size_t gcd(size_t x, size_t y)
{
if (x == 0)
return y;
if (y == 0)
return x;
size_t cf2 = ctz(x | y);
x >>= ctz(x);
for (;;)
{
y >>= ctz(y);
if (x == y)
break;
if (x > y)
std::swap(x, y);
if (x == 1)
break;
y -= x;
}
return x << cf2;
}
public:
Rational(): p(0), q(1){};
Rational(size_t a): p(a), q(1){};
Rational(size_t p, size_t q): p(p), q(q) {
reduce();
};
friend ostream& operator<< (ostream& out, const Rational& r1);
Rational operator+ (Rational& r) {
return Rational(p * r.q + q * r.p, q * r.q);
};
Rational& operator+= (Rational& r){
p = p * r.q + q * r.p;
q = q * r.q;
reduce();
return *this;
};
void reduce() {
if(q <= 1) return;
size_t cd = gcd (p,q);
if(cd > 1){
p = p / cd;
q = q / cd;
}
}
};
ostream& operator<< (ostream& out, const Rational& r)
{
out << r.p;
if(r.q > 1) out << "/" << r.q;
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment