我们知道,在数学上,当a, b都为正整数时,a/b必然是有理数(有限或者循环),那如何判断a/b是有限还是无限循环呢?程序如下:

#include <iostream>
using namespace std;

int gcd(int x, int y)
{
	int r;
	while( x % y)
	{
		r = x % y;
		x = y;
		y = r;
	}

	return y;
}

bool is2And5Number(int n)
{
	while(0 == n % 2)
	{
		n /= 2;
	}

	while(0 == n % 5)
	{
		n /= 5;
	}

	if(1 == n)
	{
		return true;
	}

	return false;
}

int main()
{
	int a, b;
	int g, n;
	while(1)
	{
		cin >> a >> b;
		g = gcd(a, b);
		n = b / g;

		if(is2And5Number(n))
		{
			cout << "finite" << endl;
		}
		else
		{
			cout << "infinite" << endl;
		}
	}

	return 0;
}


 


本文转载:CSDN博客