[英]What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
This is my code 这是我的代码
class Euler5
{
public static void main(String args[])
{
long i=2520l;
int flag= 1;
if(flag == 1)
{
search:
for(int j=10;j<=20;j++)
{
long a=i%j;
if(a!=0)
{
i+=20;
break search ;
}
if(j==20)
{
flag=0;
}
}
}
System.out.print(i);
}
}
It always print 2540. I found other way to solve it. 它总是打印2540。我发现了另一种解决方法。 But what is hitting me is why is this not working??
但是令我震惊的是为什么这不起作用?
Replace if(flag == 1)
with while (flag == 1)
. 用
while (flag == 1)
替换if(flag == 1)
while (flag == 1)
。 Otherwise you will only ever going to iterate once over the 11 values. 否则,您将只能对11个值进行一次迭代。
It is because: 这是因为:
j
by 1
. j
增加1
。 i % j
is != 0
. i % j
为!= 0
。 i
by 20
causing i = 2540
. i
递增20
导致i = 2540
。 2540
. 2540
。 It because when your for loop execute second time value of j
will be 11
which leads to your expression to 这是因为当您执行for循环时,第二次
j
值将为11
,这导致您的表达式变为
long a=2520/11
which set value of a to 1
which not satisfied your if condition and it enter your if condition 将a的值设置
a to 1
不满足您的if条件,并输入您的if条件
if(a!=0)
{
i+=20;
break search ;
}
after that it will break your for loop and terminate your execution which give output 2540 always. 之后,它将中断您的for循环并终止您的执行,始终给出输出2540。
your approach doesn't seems to be the right one. 您的方法似乎不正确。 Your for have to be from 1 to 20 not 10 to 20. And you should run all this in a while loop as Ivaylo Strandjev said.
您的for必须从1到20,而不是10到20。并且您应该像Ivaylo Strandjev所说的那样在while循环中运行所有这些。 Maybe a simpler solution is to divide 2 to 20 numbers into prime factor and add unique factors
也许一个更简单的解决方案是将2到20个数字除以质数并添加唯一因数
eg : 例如:
2 => 1 * 2
3 => 1 * 3
4 => 1 * 2 * 2
5 => 1 * 5
6 => 1 * 2 * 3
Then you keep unique one 那你就保持独一无二
1 * 2 => keep both
1 * 3 => keep only 3
1 * 2 * 2 => keep only the second 2
1 * 5 => keep only 5
1 * 2 * 3 => keep nothing
total 1 * 2 * 3 * 2 * 5 = 60 is the smallest int divisible by 2,3,4,5 and 6
You'll find 17,907,120 as your solution 您会找到17,907,120作为解决方案
I'm not good at Java :( 我不擅长Java :(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.