求分数的循环节和小数表示

参考http://www.cnblogs.com/clive/archive/2009/10/28/Circular_decimal_fraction_USCAO_2_4_5.html

用分母中2的因子个数减去分子中2的因子个数,同样用分母中5的因子个数减去分子中5的因子个数,取这两者个数的最大值,
这个就是分数的非循环部分的长度,这样偏移后,后面就是循­环部分,直到重复。

代码如下:

#include <iostream>

using namespace std;

int countBeforeRepeat(int n, int d)
{
    int  count5n = 0, count2n = 0;
	while(d % 2 == 0)
	{
		d = d/2;
		count2n++;
	}

	while(d % 5 == 0)
	{
		d = d/5;
		count5n++;
	}

	while(n % 2 == 0)
	{
		n = n/2;
		count2n--;
	}

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

	if(count2n > count5n)
	{
		if(count2n > 0) return count2n;
		else return 0;
	}else
	{
		if(count5n > 0) return count5n;
		else return 0;
	}
}

int main()
{
	int n, d;
	cin >> n >> d;
	cout << (n/d);
	cout << ".";
	
	n = n%d;
	if(n == 0)
	{
		cout << 0 << endl;
		return 0;
	}
	int count = countBeforeRepeat(n, d);
	for(int i=0; i<count; i++)
	{
		n = n*10;
		cout << (n/d);
		n = n%d;
	}

	int r = n;
	if(r != 0)
	{
		cout << "(";
		do {
			n = n*10;
            cout << (n/d);
            n = n%d;
		} while(n != r);
		cout << ")" << endl;
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值