单位分数指分子为1的分数。分母为2至10的单位分数的十进制表示如下所示: 1/2= 0.5 1/3= 0.(3) 1/4= 0.25
1/5= 0.2 1/6= 0.1(6) 1/7= 0.(142857) 1/8= 0.125 1/9= 0.(1) 1/10= 0.1
这里0.1(6)表示0.166666…,括号内表示有一位循环节。可以看出,1/7有六位循环节。 找出正整数d <
1000,其倒数的十进制表示小数部分有最长的循环节。
*** output: 983
分析:
只需要求出循环节的长度即可,任何分数都可以写成有限小数或者无限循环小数,如果是有限的好说,
如果是无限的,通过不断的求余运算,计算出mod,然后直到找到第一个出现重复的即可。
用听得懂的话来说:
定理 ------ 能用分数表示的数都是有理数,有理数的无限小数必有循环节
所以,不要从结果上去验证小数部分何时循环,有循环说明除的过程中出现了相同的余数
https://blog.csdn.net/qq_28394425/article/details/53083685
public static int reciprocalCycles() {
int max = 0;
int target = 0;
for(int i=1; i<1000; i++) {
int circu_count = circulation(1,i); //circulation(被除数, 除数)
//找出最长的循环节
if(circu_count > max) {
max = circu_count;
target = i;
}
}
return target;
}
/**@ circulation(a 被除数, b除数)
* @ return 循环节的长度
* ***/
public static int circulation(int a, int b) {
ArrayList<Integer> quoList = new ArrayList<Integer>();
ArrayList<Integer> modList = new ArrayList<Integer>();
int index = -1; //记录小数的位数
while(true) {
quoList.add(a/b); //整除 0
int mod = a % b; //求余 mod 1
if(mod == 0) {
break;
}
index = modList.indexOf(mod); // 1 3
//如果之前出现过,这里开始循环,直接退出
if(index >= 0) {
break;
}
else {
modList.add(mod);
}
a = mod * 10;
}
//说明出现过循环
if(index >= 0) {
return quoList.size() - (index + 1);
}
//没有出现过循环
else {
return 0;
}
}
public static void main(String[] args) {
System.out.println(reciprocalCycles());
}