Output is not getting displayed

140 Views Asked by At

I am writing a simple java program to find the smallest number which is divisible by all the numbers from 1 to 20.

I have written the following code:

package smallmultiple;
public class SmallMultiple { 
    public static void main(String[] args) {
        int sml = 0;
        outerloop:
        for (int i = 40; i < 100000; i++) {
            int j=1;
            do {
                if(i%j==0)
                    j++;                
            } while(j<21);

            if(j==20) {
                sml=i;
                break outerloop;
            } 
        }

        System.out.println(sml);
    }
}

It is not giving any error but it is not giving any output.

4

There are 4 best solutions below

0
Rahul Tripathi On

You can try this which is a bit faster than yours solution:-

for(int i = 190; ; i += 190) {
        if(i % 3 == 0 
                && i % 4 == 0
                && i % 6 == 0 
                && i % 7 == 0
                && i % 8 == 0 
                && i % 9 == 0
                && i % 11 == 0
                && i % 12 == 0 
                && i % 13 == 0 
                && i % 14 == 0 
                && i % 15 == 0
                && i % 16 == 0
                && i % 17 == 0
                && i % 18 == 0
                && i % 20 == 0) {
            System.out.println(i);
            break;
        }
    }

You can also check out this article.

0
sanbhat On

You are incrementing j only if i is perfectly divisible by j. Shouldn't you break or exit the do.. while loop of atleast one number is not divisible? Not doing so is causing infinite loop I believe. It should be something like

if(i%j==0) {
   j++;
}
else {
  break;
}  
0
ntlam On

its simple. Let me explain your loop. First, i = 40 and j = 1, its ok. Then j++.Next i = 40 and j = 2, its still correctly. Then j++ again. Now i = 40, j = 3 and i%j !=0 => j cannot ++ and j still equal 3. And you see, j = 3 is still satisfy your loop ( j < 21) then it loop and loop forever. This is the reason why you cant get any output. You can use your IDE debugging to find this mistake. Sorry my English not good.

0
IBJ On

In java, to respect the object oriented best practise, it's not advised to user labels, try this :

public class NumberTool {

    public static void main(String[] args) {
        System.out.println("Smallest number is : " + getSmallestNumberDividedByOneToTwnety());
    }

    public static int getSmallestNumberDividedByOneToTwnety() {

        for ( int i = 40; i <= 2147483647; i++) {

            if (isNumberDivdedByOneToTwenty(i)) {
                return i;
            }

        }

        return 0;
    }

    public static boolean isNumberDivdedByOneToTwenty(int numberToTest) {

        for (int i = 1; i <= 20; i++) {
            if (numberToTest % i != 0) {
                return false;
            }
        }

        return true;

    }

}

Output is:

Smallest number is : 232792560