File indexing completed on 2024-05-12 05:55:18

0001 // This file is part of the SpeedCrunch project
0002 // Copyright (C) 2015 Pol Welter <polwelter@gmail.com>
0003 //
0004 // This program is free software; you can redistribute it and/or
0005 // modify it under the terms of the GNU General Public License
0006 // as published by the Free Software Foundation; either version 2
0007 // of the License, or (at your option) any later version.
0008 //
0009 // This program is distributed in the hope that it will be useful,
0010 // but WITHOUT ANY WARRANTY; without even the implied warranty of
0011 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0012 // GNU General Public License for more details.
0013 //
0014 // You should have received a copy of the GNU General Public License
0015 // along with this program; see the file COPYING.  If not, write to
0016 // the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
0017 // Boston, MA 02110-1301, USA.
0018 
0019 #ifndef RATIONAL_H
0020 #define RATIONAL_H
0021 
0022 class HNumber;
0023 class QString;
0024 
0025 class Rational
0026 {
0027     int m_num;
0028     int m_denom;
0029     bool m_valid;
0030 
0031     inline int gcd(int a, int b) const {return (b==0) ? a : gcd(b, a%b);}
0032     void normalize();
0033     int compare(const Rational & other) const;
0034 
0035 public:
0036     Rational() : m_num(0), m_denom(1), m_valid(true) {}
0037     Rational(const HNumber &num);
0038     Rational(const double &num);
0039     Rational(const QString & str);
0040     Rational(const int a, const int b) : m_num(a), m_denom(b), m_valid(true) {normalize();}
0041 
0042     int numerator() const {return m_num;}
0043     int denominator() const {return m_denom;}
0044 
0045     Rational operator*(const Rational & other) const;
0046     Rational operator/(const Rational & other) const;
0047     Rational operator+(const Rational & other) const;
0048     Rational operator-(const Rational & other) const;
0049     Rational &operator=(const Rational & other);
0050     Rational &operator+=(const Rational & other);
0051     Rational &operator-=(const Rational & other);
0052     Rational &operator*=(const Rational & other);
0053     Rational &operator/=(const Rational & other);
0054     bool operator<(const Rational & other) const;
0055     bool operator==(const Rational & other) const;
0056     bool operator!=(const Rational & other) const {return !operator==(other);}
0057     bool operator>(const Rational & other) const;
0058 
0059     bool isZero() const;
0060     bool isValid() const;
0061 
0062     QString toString() const;
0063     HNumber toHNumber( )const;
0064     double toDouble() const;
0065 };
0066 
0067 #endif // RATIONAL_H