【发布时间】:2013-01-10 21:11:01
【问题描述】:
我有以下算法来确定两个数字 x 和 y 的最大公约数。我需要找到描述该算法的大符号并解释原因,但我不知道如何做到这一点。
有人可以看看我的代码并解释一下它是什么类型的大哦符号吗?
public void question1(int x, int y){
ArrayList divisorx = new ArrayList(); //the list of divisors of number x
ArrayList divisory = new ArrayList();//divisors of number y
ArrayList answerSet = new ArrayList();//the common divisors from both
//divisorx and divisory
for(int i=1; i<=x; i++){//this loop finds the divisors of number x and
//adds them to divisorx
double remainder = x%i;
if(remainder==0){
//i is a divisor
divisorx.add(i);
}
}
for(int i2=1; i2<=y; i2++){//this loop finds the divisors of number y
//and adds them to divisory
double remainder2 = y%i2;
if(remainder2==0){
//i2 is a divisor
divisory.add(i2);
}
}
int xsize = divisorx.size();
int ysize = divisory.size();
for(int i=0; i<xsize; i++){//this massive loop compares each element of
//divisorx to those of divisory to find common divisors. It adds those common
//divisors to the arraylist answerSet
for(int j=0; j<ysize; j++){
if(divisorx.get(i)==divisory.get(j)){
//common divisor has been found
//add it to an answer array
answerSet.add(divisorx.get(i));
}
}
}
Collections.sort(answerSet);//sorts the answerSet from smallest to greatest
Object gcd = answerSet.get(answerSet.size()-1);//get the last element of the
//arraylist, which is the gcd
System.out.print("Your Answer: "+gcd);//print out the greatest common divisor
}
【问题讨论】:
-
看看循环和操作。例如。你
sort一个集合排序成本至少 O(n log n) -
一个起点是计算每行代码执行了多少次。很多行只执行一次,因此您主要需要密切注意循环。在这种特殊情况下,您的“计数”将根据 x 和 y。
-
当你计算这样的东西时,重要的是查看每个数字的位数。根据幅度进行分析比较棘手。
-
上述算法中有很多操作可以很容易的清理。例如,您可以执行 x->2,而不是从 1->x 开始。这将消除嵌套循环并用类似合并的小操作替换排序。即使您没有实现欧几里得方法,当前的代码似乎也是一种尽可能减慢直率方式的方法。