附上题目:
分子为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的循环圈。可以看出1/7拥有一个6位的循环圈。
找出小于1000的数字d,1/d 的十进制表示含有最长的循环圈。
原题:A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
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
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
解题思路:
一时半会确实想不到思路,不妨写一些除法运算试试,取题目中最难处理的1/7,
次数 商 余数
1 0 0
2 1 3
3 4 2
4 2 6
5 8 4
6 5 5
7 7 1
8 1 3
由上图可知当商的小数点中出现循环,那么计算过程中的余数也会出现循环,当出现与第一个与第二次计算时一样的解时,就可以得到这个循环节的长度,同时要注意所有的循环小数,循环节最多为分母-1,如果不是循环小数,直接pass掉就可以,如下是java的代码:
public class Launcher {
public static void main(String[] args) {
Vector<Integer> loop=new Vector<Integer>();
int n =1;
int size=0;
int max=0;
int d=0;
for(int i=2;i<1000;i++){
while(n<i){
n*=10;
}
while(n>=i){
n=n%i;
if(n==0){
n=1;
}
loop.add(n);
if(n==loop.get(0)&&loop.size()>1){
size=loop.size()-1;
break;
}
while(n<i){
n*=10;
}
if(loop.size()==i-1){
break;
}
}
n=1;
if(max<size){
max=size;
d=i;
}
loop.removeAllElements();
}
System.out.println(d);
}
}