user2644549
user2644549

Reputation: 141

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. But what is hitting me is why is this not working??

Upvotes: 0

Views: 1525

Answers (4)

dagfr
dagfr

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

Yagnesh Agola
Yagnesh Agola

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

Ravinder Reddy
Ravinder Reddy

Reputation: 24022

It is because:

  1. after first iteration, you are increasing j by 1.
  2. on the second iteration i % j is != 0.
  3. in if condition, you are incrementing i by 20 causing i = 2540.
  4. you are breaking the loop there.
  5. and hence the result is 2540.

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

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

Related Questions