Is there better way of iteration to find the evenly divisible number?

Hamster The Rat :

I'm trying to solve this problem: "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?"

Please, do not tell me the answer, I really want to solve it by myself. All I need is an advice regarding math aspect of the question. The thing is adding one every cycle isn't a good idea because the process is too slow. Or is there a problem with variable type not being long?

I've tried to get number which is evenly divisible of all numbers between (1 and 10), and even (1 and 17), and the algorithm worked well.

int in_num = 1;
int score = 0;
public void calculate() {
    while (true) {
        score = 0;
        for (int x = 1; x < 21; x++) {
            if ((in_num%x) == 0) {
                score++;
            }
        }
        System.out.println("Number " + in_num + " has " + score );
        if (score == 20) {
            System.out.println(in_num);
            break;
        }
        in_num++;
    }

I expect the specific integer, but I get infinite loop.

Matt Timmermans :

The lowest common multiple of two numbers x and y is xy/GCD(x,y), where GCD calculates the greatest common divisor.

You can implement GCD easily using Euclid's algorithm or the binary GCD algorithm: https://en.wikipedia.org/wiki/Greatest_common_divisor

The algorithm would be like:

result = 1;
for (x = 20; x > 0; --x)
    result *= (x/GCD(x,result));

Of course this works for other numbers as well. If you really don't care about that, then you can just print 232792560

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141932&siteId=1