一个简单的数学题
时间限制:3000 ms | 内存限制:65535 KB
难度:3
描述
zyc最近迷上了数学,一天,dj想出了一道数学题来难住他。算出1/n,但zyc一时答不上来希望大家能编程帮助他。
输入
第一行整数T,表示测试组数。后面T行,每行一个整数 n (1<=|n|<=10^5).
输出
输出1/n. (是循环小数的,只输出第一个循环节).
样例输入
4
2
3
7
168
样例输出
0.5
0.3
0.142857
0.005952380
----------------------------------------------------------------------------------------------------------------------------
在网上找了一下String类找重复的方法,没有找到,于是自己写了一个方法
开始只想到0.123123123这种类型 当时还有0.AB123123123 所以后面就直接写的静态方法在传入数据
上代码 不多说
class Simple{
private double num[]=new double[100];
public Simple(int ...x) {
// System.out.println(x.length);
int i=0;
for(int t:x){
this.num[i]=1.0/t;
i++;
}
}
public String[] getInfo() {
String temp[]=new String[10];
int i=0;
for(double x:this.num){
if(x!=0.0)
temp[i++]=cycle(String.valueOf(x));
}
return temp;
}
public String cycle(String str){
String temp[]=str.split("\\.");//将数据 分割成 小数点以前 小数点以后 然后处理小数点以后的数据
temp[0]="";
while(temp[1].startsWith("0")){
temp[0]+=0;
temp[1]=temp[1].substring(1);
}//temp[1]是纯数据,前面是没有0的
//然后分割temp[1]
temp[1]=temp[1].trim();
int i=0;
while(true) {
//第二次分割 依次TwoSpli从1 到temp[1].length()的长度,依次和后面做比对
String TwoSplit=temp[1].substring(0, ++i);
if(i>temp[1].length()/2){ //temp[1]的数据不足平分 则此数据不循环
return str;
}
else{
String NewStr=temp[1].substring(i,TwoSplit.length()+i); //取得TwoSplit后面相同长度的数据作比较
if(TwoSplit.equals(NewStr)){//比较成功
return "0."+temp[0]+TwoSplit;
}
}
}
}
}
public class SimapleMath {
public static void main(String[] args) {
Simple s=new Simple(2,3,7,168);
String str[]=s.getInfo();
for(String g:str)
if(g!=null){
if(g.length()>10)
ditto(g);
else System.out.println(g);
}
}
public static void ditto(String str) {
String temp[]=str.split("\\.");//将数据 分割成 小数点以前 小数点以后 然后处理小数点以后的数据
temp[0]="";
while(temp[1].startsWith("0")){
temp[0]+=0;
temp[1]=temp[1].substring(1);
}//temp[1]是纯数据,前面是没有0的
//然后分割temp[1]
// System.out.println(temp[0]+" "+temp[1]);
temp[1]=temp[1].trim();
int i=0;
String ditto;
String dittoData="";
while(true) {
// System.out.println(dittoData+" --- "+temp[1]);
if(i>temp[1].length()/2)
break;
dittoData+=temp[1].substring(0, 1);
temp[1]=temp[1].substring(1);
dittoData+=iterate(temp[1]);
if(iterate(temp[1])!="")
break;
}
System.out.println("0."+temp[0]+dittoData);
}
public static String iterate(String str){
String temp;
String iterate;
int i=0;
while(true) {
temp=str.substring(0, ++i);
if(i>str.length()/2){
break;
}else{
iterate=str.substring(i, temp.length()+i);
if(temp.equals(iterate))
return temp;
}
}
return "";
}
}
// 如何寻找循环小数的第一个循环
// 思路,先把doule数变为String 在通过
//0.1234 1234 12345.