欧拉计划26题是计算1/d(d<1000)中,循环小数最长循环节的题目。我将小数点后面的每个数字存放在一个ArrayList中,然后开始寻找循环节。一切尽在代码中!
import java.util.*;
public class PE26 {
private static int Length = 1000;
private static String str;
private static int count1 = 0, D = 1000;
private static int[][] Record = new int[D][2]; //用于存放d的值和它循环节的长度
public static void main(String[] args) {
// TODO Auto-generated method stub
List <Integer> loop = new ArrayList();
for(int d=1;d<=D;d++){
loop = LoopArray(d);
// System.out.print(d + ":" + loop + str );
// System.out.println(); //这两行用于输出1/d的小数部分
}
// for(int j=0;j<D;j++){
// System.out.println(Record[j][0] + "," + Record[j][1]);
// }
Sort(Record); //对循环节的长度进行排序
}
private static List<Integer> LoopArray(int num) {
// TODO Auto-generated method stub
int div = 0,rem = 0,count;
str = null;
List <Integer> LArray = new ArrayList();
List <Integer> ModArray = new ArrayList();
div = 1/num;rem = 1%num;
count = rem;
//while(true){
for(int i=0;i<Length;i++){
div = rem*10/num;
count = (rem*10%num)*10%num;
rem = rem*10%num;
//判断当前商是否有存在于LArray中
if(Judge(LArray,div) && Judge(ModArray,count) && (rem == ModArray.get(LArray.indexOf(div)))){
Record[count1][0] = num;
Record[count1][1] = i- LArray.indexOf(div);
count1 ++;
break;
}else{
LArray.add(div);
ModArray.add(rem);
}
if(rem == 0){ //能整除的小数
str = "能被整除的数";
break;
}else
str = "不能被整除的数";
}
return LArray;
}
private static boolean Judge(List<Integer> larray,int div){
boolean flag = false;
if(larray.contains(div)){
flag = true;
}
return flag;
}
private static void Sort(int[][] record) {
// TODO Auto-generated method stub
int a,b;
for(int i=0;i<D;i++){
for(int k=i;k<D;k++){
if(record[i][1]>record[k][1] && record[k][1] != 0){
a = record[k][1]; b = record[k][0];
record[k][1] = record[i][1]; record[k][0] = record[i][0];
record[i][1] = a; record[i][0] = b;
}
}
}
for(int j=0;j<D;j++){
System.out.println(record[j][0] + "," + record[j][1]);
}
}
}