我试图找到能被 1 到 20 的所有数字整除的最小正数。我们知道 2520 是可以被 1 到 10 的每个数字整除的最小数字,而无需任何剩余。我的 find() 找到从 2520 开始的数字,该数字可被 1-20 的所有数字整除,但由于某种原因返回 2520。我找不到我的 find() 有什么问题?
public class Solution {
public ArrayList<Integer> list = new ArrayList<Integer>();
// creating a list of integers from 1 to 20
public ArrayList<Integer> addtolist() {
for (int i = 1; i <= 20; i++) {
list.add(i);
}
return list;
}
// finds the smallest positive number that is evenly divisible by all
of the numbers from 1 to 20
public int find() {
int num = 2520;
while(true) {
for(int i: list) {
if(num % i == 0) {
return num;
}
else {
num = num + 1;
}
}
}
}
public static void main(String[] args) {
Solution sol = new Solution();
sol.addtolist();
System.out.println(sol.find());//2520
}
}
最佳答案
如果 list
中的 any i
将它除,你的 find
函数返回 num
.如果 num
中的 every i
是除数,它应该只返回 num
。
虽然不得不说这远不是解决问题的最有效方法。
关于java - 试图找到能被 1 到 20 的所有数字整除的最小正数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50194080/