HDU 2522 A simple problem( 分数循环节 )


**链接:****Here! **

思路:模拟除法,当余数再次出现的时候一定是遇到了循环节( 可看下图例子 ),否则的话继续除法的步骤,直到被除数为 0 。

图一

注意:这道题不需要重新申请一个数组来单独存放答案,如果符合要求直接输出即可,如果申请一个数组来存放答案,每次都需要情况答案数组,极大的浪费了时间,很容易T


/*************************************************************************
    > File Name: hdu2522.cpp
    > Author:    WArobot 
    > Blog:      http://www.cnblogs.com/WArobot/ 
    > Created Time: 2017年06月28日 星期三 16时24分24秒
 ************************************************************************/

#include <stdio.h>
#include <string.h>

#define MAX_RANGE 100000				// .. 一定得开大点!

int HowManyReciprocalCycles(int n) {	// 返回分数循环节的长度
	int rest[MAX_RANGE + 10] = {0};
	int ret = 1 , ind = 0;
	while (rest[ret] == 0 && ret) {
		rest[ret] = ++ind;
		ret *= 10;
		printf("%d",ret / n);
		ret %= n;
	}
	return ret ? ind - rest[ret] : 0;
}
int main() {
	int T , n , flag;
	scanf("%d",&T);
	while (T--) {
		scanf("%d",&n);
		if (n < 0)	printf("-") , n = -n;
		if (n == 1)	{	
			printf("1
");	continue;
		}
		printf("0.");
		int ret = HowManyReciprocalCycles(n);
		printf("
");
	}
	return 0;
}
原文地址:https://www.cnblogs.com/WArobot/p/7091333.html