Loading [MathJax]/extensions/TeX/newcommand.js
\newcommand{\ord}[1]{\mathcal{O}\left(#1\right)} \newcommand{\abs}[1]{\lvert #1 \rvert} \newcommand{\floor}[1]{\lfloor #1 \rfloor} \newcommand{\ceil}[1]{\lceil #1 \rceil} \newcommand{\opord}{\operatorname{\mathcal{O}}} \newcommand{\argmax}{\operatorname{arg\,max}} \newcommand{\str}[1]{\texttt{"#1"}}

2015年9月23日 星期三

[ Fraction ] 分數模板

今天學弟的比賽剛結束,因為有考到相關內容所以到現在才釋出分數模板。
因為每種題目要求輸出的分數格式都不一樣,所以不提供輸出的程式,必定約到最簡分數。
以下提供模板:
/************************
n為分子,d為分母
若分數為0則n=0,d=1
若為負數則負號加在分子
必定約到最簡分數
************************/
#ifndef SUNMOON_FRACTION
#define SUNMOON_FRACTION
#include<algorithm>
template<typename T>
struct fraction{
T n,d;
fraction(const T &_n=0,const T &_d=1):n(_n),d(_d){
T t=std::__gcd(n,d);
n/=t,d/=t;
if(d<0)n=-n,d=-d;
}
fraction operator-()const{
return fraction(-n,d);
}
fraction operator+(const fraction &b)const{
return fraction(n*b.d+b.n*d,d*b.d);
}
fraction operator-(const fraction &b)const{
return fraction(n*b.d-b.n*d,d*b.d);
}
fraction operator*(const fraction &b)const{
return fraction(n*b.n,d*b.d);
}
fraction operator/(const fraction &b)const{
return fraction(n*b.d,d*b.n);
}
fraction operator+=(const fraction &b){
return *this=fraction(n*b.d+b.n*d,d*b.d);
}
fraction operator-=(const fraction &b){
return *this=fraction(n*b.d-b.n*d,d*b.d);
}
fraction operator*=(const fraction &b){
return *this=fraction(n*b.n,d*b.d);
}
fraction operator/=(const fraction &b){
return *this=fraction(n*b.d,d*b.n);
}
bool operator <(const fraction &b)const{
return n*b.d<b.n*d;
}
bool operator >(const fraction &b)const{
return n*b.d>b.n*d;
}
bool operator ==(const fraction &b)const{
return n*b.d==b.n*d;
}
bool operator <=(const fraction &b)const{
return n*b.d<=b.n*d;
}
bool operator >=(const fraction &b)const{
return n*b.d>=b.n*d;
}
};
#endif
view raw fraction.cpp hosted with ❤ by GitHub

4 則留言: