Reputation: 141
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. But what is hitting me is why is this not working??
Upvotes: 0
Views: 1525
Reputation: 2384
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. Maybe a simpler solution is to divide 2 to 20 numbers into prime factor and add unique factors
e.g. :
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
I'm not good at Java :(
Upvotes: 1
Reputation: 4657
It because when your for loop execute second time value of j
will be 11
which leads to your expression to
long a=2520/11
which set value of a to 1
which not satisfied your if condition and it enter your if condition
if(a!=0)
{
i+=20;
break search ;
}
after that it will break your for loop and terminate your execution which give output 2540 always.
Upvotes: 1
Reputation: 24022
It is because:
j
by 1
. i % j
is != 0
. i
by 20
causing i = 2540
. 2540
. Upvotes: 1
Reputation: 71019
Replace if(flag == 1)
with while (flag == 1)
. Otherwise you will only ever going to iterate once over the 11 values.
Upvotes: 3