0

I have been going through the Euler project problems one by one every day and asking whatever questions I have on this website. The problem description is commented out in the code. This time around, I don't have any particular problems with my code, but I was wondering if there is any way to improve or optimize it. I am a beginner, so it would be helpful to hear any suggestions. Here is the code in Java:

    //2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
    //What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
    int smallest = 0;
    for(int num = 2520; num < 1000000000; num += 2520) {
        boolean isMultiple = true;
        for (int multiple = 20; multiple >= 11; multiple--) {
            if (num % multiple != 0) {
                isMultiple = false;
                break;
            }
        }
        if (isMultiple) {
            smallest = num;
            break;
        }
    }
    System.out.println("The LCM of all the numbers between one and twenty is : " + smallest);
Vasila_M
  • 53
  • 6
  • Not from an optimization perspective, but you can expand the range of `num` up to `Integer.MAX_VALUE - 2520`. – Arvind Kumar Avinash Jan 24 '21 at 07:07
  • See also discussion at https://stackoverflow.com/q/13719768/14955 – Thilo Jan 24 '21 at 07:09
  • Observing that the least common multiple of two numbers is the product of the numbers divided by the GCD of the numbers gives some hint how to optimize this. – Henry Jan 24 '21 at 08:25

0 Answers0