分类: C/C++
2013-01-02 14:45:45
#include using namespace std; bool IsPowerOfN(unsigned int number,unsigned int n) { if (number<2) { return number==1; } switch(n) { case 0: return number==0; case 1: return number!=0; case 2: while((number & 0x01) == 0 && number > 2) { number >>= 1; } return number == 2; default: while(number % n == 0 && number > n) { number /= n; } return number == n; } } unsigned int MaxCommonFactor(unsigned int a,unsigned int b) { unsigned int min = a>b?b:a, max = a>b?a:b; if (max%min == 0 || min == 1) { return min; } for (unsigned int i = min/2;i>0;i--) { if (a%i == 0 && b%i == 0) { return i; } } return 1; } bool IsFiniteDecimals(unsigned int numer,unsigned int denom) { //处理假分数 while(numer > denom) { numer -= denom; } //化为最简分数 denom /= MaxCommonFactor(numer,denom); //判断是否为2或5的幂 if (IsPowerOfN(denom,2)||IsPowerOfN(denom,5)) { return true; } else { //判断是否只有2和5两个因数 while((denom & 0x01) == 0) { denom >>= 1; } return IsPowerOfN(denom,5); } } int main() { cout<<"5/30 :"<<(IsFiniteDecimals(5,30)?"Finite":"Infinite")<<endl; cout<<"45/30 :"<<(IsFiniteDecimals(45,30)?"Finite":"Infinite")<<endl; cout<<"3/17 :"<<(IsFiniteDecimals(3,17)?"Finite":"Infinite")<<endl; return 0; } |
Output: