求分数对应循环小数的循环体

又一道笔试题,就是给定一个分数,分子为X,分母为Y,如果它是循环小数,则输出该循环小数的循环部分。
要使某位在小数部分循环出现,就是要使此时的余数和之前某位的余数相等,整理下思路,分子除以分母得到余数,然后余数乘以10再除以分母得到下一个余数,如此循环做下去,看看此时的余数有没跟之前余数相等的,有的话,它就是循环小数,也就找到循环体了。

#include <stdio.h>
#define N  1000

int checkSame(int a[], int maxIndex, int checkValue)
{
    int j;
    for(j = 0; j <= maxIndex; j++)
        if(a[j] == checkValue)
            return j;
    return -1;
}

void findRecurringDigits(int x, int y)
{
    int i=0;
    int quotient, remainder, checkFlag, k;
    int quotients[N], remainders[N];
    remainder = x % y;
    if(remainder == 0){
        printf("Be divided with no remainder.\n");
        return;
    }
    remainders[0] = remainder;
    while(true){
        quotient = remainder * 10 / y;
        remainder = remainder * 10 % y;
        if(remainder == 0)
            return;
        quotients[i] = quotient;
        checkFlag = checkSame(remainders, i, remainder);
        if(checkFlag >= 0){
            //print the recurring digits
            for(k = checkFlag; k <= i; k++)
                printf("%d", quotients[k]);
            printf("\n");
            return;
        }
        if( i+1 >= 1000){
            printf("The recarring part is too long to catch.\n");
            return;
        }
        remainders[++i] = remainder;
    }
}

int main()
{
    int a, b;
    scanf("%d %d", &a, &b);
    findRecurringDigits(a, b);
    return 0;
}

 

因为是否正负不影响循环部分,所以这里就只考虑分子,分母都为正数的情况。
验证了下:1/3 , 3/7 , 2/1...应该没什么问题了吧

posted @ 2013-03-03 16:46  sillypudding  阅读(462)  评论(0)    收藏  举报