Uva202循环小数

输入a,b两个整数求其商的循环节。

分析:高精度,以数组代替小数位。根据抽屉原则,a/b的余数只能是0~b-1所以计算b+1次必定有余数重复,再进行10*n/m重复的余数之后的余数必定与之前的对应相等。开数组将余数和商保存输出即可。另开数组记录余数是否出现过。

代码

#include<iostream>//抽屉原则
#include<cstring>
using namespace std;
int main()
{
    int sh[3003],yu[3003],mark[3003];//sh用来记录商,yu记录余数,mark记录余数出现的位置。
    int n,m,t;
    while(cin>>n>>m)
    {
        int count=0;
        memset(sh,0,sizeof(sh));
        memset(mark,0,sizeof(mark));
        sh[count++]=n/m;
        n%=m;
        while(n&&!mark[n])
        {
            //cout<<'.';
            mark[n]=count;
            yu[count]=n;
            sh[count++]=(10*n)/m;
            n=10*n%m;
        }
        cout<<sh[0]<<'.';
        for(int i=1;i<count&&i<=50;i++)
        {
            if(n&&yu[i]==n)
                cout<<'(';
            cout<<sh[i];
        }
        if(!n)    cout<<"(0";
        if(count>50)    cout<<"...";
        cout<<')'<<endl;
        int ans=count-mark[n];
        if(n==0)    ans=1;
        cout<<"循环节长度为:"<<ans<<endl;
    }
    return 0;
}

 

posted @ 2016-07-10 18:46  Depth  阅读(1456)  评论(0编辑  收藏  举报