gpt4 book ai didi

java - 打印并返回正确的列表

转载 作者:行者123 更新时间:2023-12-01 22:31:10 27 4
gpt4 key购买 nike

我目前正在研究以下问题

// It should return the greatest common factor
// between two numbers.
//
// Examples of greatestCommonFactor:
// greatestCommonFactor(6, 4) // returns 2
// greatestCommonFactor(7, 9) // returns 1
// greatestCommonFactor(20, 30) // returns 10
//
// Hint: start a counter from 1 and try to divide both
// numbers by the counter. If the remainder of both divisions
// is 0, then the counter is a common factor. Continue incrementing
// the counter to find the greatest common factor. Use a while loop
// to increment the counter.

我的代码如下所示

public static List greatestCommonFactor(int a, int b){
int i = 1 ;
List topnum = new ArrayList();
ArrayList <Integer> factor = new ArrayList<Integer>();
while (i <= a || i <= b ){
i++;
}
if (a%i == 0 && b%i == 0){
factor.add(i);
}
else if (a%i <= 1 || b%i <= 1){
Collections.sort(factor);
List<Integer> topnum1 = factor.subList(factor.size() - 1, factor.size());

}
return topnum;
}

我在获得正确的输出时遇到问题。目前我得到 []作为输出,这很奇怪。我似乎无法得到topnum进入List<Integer>也没有出现错误,所以这就是我可以管理的。

任何人都有任何提示可以让我打印 topnum1 中的元素来解决这个教程?

最佳答案

你的 while 循环什么也不做。您可能应该将您的条件放入其中,否则只会测试 i 的最后一个值。

while (i <= a || i <= b ){
if (a%i == 0 && b%i == 0){
factor.add(i);
}
i++;
}

除此之外,您还可以将元素添加到 factor列表(至少在修复后您会这样做),并将该列表的最后一个元素放入 topnum1 中,但你的方法返回 topnum它仍然是空的。

最后,你的else if (a%i <= 1 || b%i <= 1)我不清楚。而且您不需要对 factor 进行排序列表。它已经被排序了。实际上,你根本不需要那个列表,只需保留最大的 i 即可。这是一个公因子并返回它。

这将使代码更加简单:

public static int greatestCommonFactor(int a, int b)
{
int result = 1;
int i = 1 ;
while (i <= a && i <= b){
if (a%i == 0 && b%i == 0){
result = i;
}
i++;
}

return result;
}

关于java - 打印并返回正确的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27721389/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com