![](/img/trans.png)
[英]What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
[英]Trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20
我試圖找到最小的正數,該數可以被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
任何 i
將其分割,則find
函數將返回num
。 它應該只返回num
如果每一個 i
在num
是一個除數。
盡管必須說,這遠非最有效的解決方案。
當(num % i == 0)
,您將從for循環中返回,因為我始終從1開始。 相反,您需要等到最后返回:
public int find() {
int num = 2520;
while(true) {
boolean allDivisible = true;
for(int i: list) {
if(num % i != 0) {
allDivisible = false;
break;
}
}
if (allDivisible) {
return num;
else {
num = num + 1;
}
}
}
在您的代碼中:
for(int i: list) {
if(num % i == 0) {
return num; // Returns immediately.
}
else {
num = num + 1;
}
}
在列表中找到匹配的數字后,您將立即返回。 您只想在找到與列表中的所有值都匹配的值時才返回。
好問題!
long answer = LongStream.iterate(1, n -> n + 1)
.filter(n -> IntStream.rangeClosed(1, 20).allMatch(f -> n % f == 0))
.findFirst().getAsLong();
答案是232792560
顯然,使用數學有很多捷徑(例如,僅查看偶數,而忽略1到20中的數字,這是該范圍內其他數字的因數)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.