[英]Trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20
I'm trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20. We are given that 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. 我试图找到最小的正数,该数可以被1到20的所有数均分。我们认为2520是可以除以1到10的每个数而没有任何余数的最小数。 My find() finds the number starting from 2520 that is divisible by all numbers from 1-20 but is returning 2520 for some reason.
我的find()查找从2520开始的数字,该数字可被1-20的所有数字整除,但由于某种原因返回2520。 I cannot find what's wrong about my find()?
我找不到我的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
}
}
Your find
function returns num
if any i
in list
divides it. 如果
list
任何 i
将其分割,则find
函数将返回num
。 It should only return num
if every i
in num
is a divisor. 它应该只返回
num
如果每一个 i
在num
是一个除数。
Although it has to be said that this is far from the most efficient solution to the problem. 尽管必须说,这远非最有效的解决方案。
You return from the for loop when (num % i == 0)
, given that i starts at 1 this always true. 当
(num % i == 0)
,您将从for循环中返回,因为我始终从1开始。 Instead you need to wait until the end to return: 相反,您需要等到最后返回:
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;
}
}
}
In your code: 在您的代码中:
for(int i: list) {
if(num % i == 0) {
return num; // Returns immediately.
}
else {
num = num + 1;
}
}
you return as soon as you find some number in the list that has a match. 在列表中找到匹配的数字后,您将立即返回。 What you want to do is only return when you have found a value that matches all in the list.
您只想在找到与列表中的所有值都匹配的值时才返回。
Nice question! 好问题!
long answer = LongStream.iterate(1, n -> n + 1)
.filter(n -> IntStream.rangeClosed(1, 20).allMatch(f -> n % f == 0))
.findFirst().getAsLong();
Answer is 232792560 答案是232792560
There are obviously plenty of shortcuts using math (eg only looking at even numbers, ignoring numbers in 1 to 20 that are factors of other numbers in that range). 显然,使用数学有很多捷径(例如,仅查看偶数,而忽略1到20中的数字,这是该范围内其他数字的因数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.