【发布时间】:2016-10-20 18:40:35
【问题描述】:
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
if(t<1 || t>100){System.exit(0);}
ArrayList a=new ArrayList<>();
for(int i=0;i<t;i++){
String s=in.next().toString();
String s2=in.next().toString();
int count=0;
int first=Integer.parseInt(s);
int last=Integer.parseInt(s2);
if(first<1 || last>1000000000){System.exit(0);}
for(int k=first;k<=last;k++){
int sqrt =(int)Math.sqrt(k);
if(sqrt*sqrt==k){count++;}
}
a.add(count);
}
Iterator it=a.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
在这个程序中,当我提供大量输入时,需要花费大量时间来提供输出。谁能告诉我如何优化这个程序。 该程序用于查找平方根数。 输入:第一行包含 ,测试用例的数量 T.T 测试用例,每个都在一个新行中。 每个测试用例包含两个以空格分隔的整数,分别表示 s 和 s2。
示例输入
2
3 9
17 24
样本输出
2
0
大输入:
35
465868129 988379794
181510012 293922871
395151610 407596310
481403421 520201871
309804254 776824625
304742289 566848910
267554756 828997506
387224568 926504395
244571677 871603971
444567315 582147918
334350264 342469009
400474096 410940967
488907300 943628573
26441071 801576263
182001128 267557939
115732998 974318256
192538332 862327048
45429427 307805497
358658006 842644090
92930998 431601473
231163983 893672132
275221547 298953978
351237326 981399371
484598992 985428966
103405553 529324202
37393469 768655346
30179914 482808626
208821550 538302223
154654533 791652309
68424067 854065374
246956110 517538724
51395253 876949418
57778758 368742600
227566632 606529208
【问题讨论】:
-
什么是大输入?所有大于 100 的都停止程序
-
@KevinEsche 14 465868129 988379794 181510012 293922871 395151610 407596310 481403421 520201871 309804254 776824625 304742289 566848910 267554756 828997506 387224568 926504395 244571677 871603971 444567315 582147918 334350264 342469009 400474096 410940967 488907300 943628573 26441071 801576263 182001128 267557939
-
好吧,进行 14 次迭代并在那里进行数百万次循环会导致执行时间稍长...
-
我不明白您为什么需要循环执行此操作:只能有小于
1000000000的sqrt(1000000000)完美正方形,即大约 30k 个数字。只需将它们全部枚举一次,然后根据您需要的范围计算它们。 -
另外,一旦你找到了一个完美的正方形,你就可以直接跳到下一个:它只是
(1+sqrt)^2。无需检查中间的所有数字。
标签: java optimization