Smallest Multiple Algorithm using Bruteforce or GCD/LCM

  • 时间:2020-09-10 12:45:51
  • 分类:网络文摘
  • 阅读:89 次

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?

Bruteforce Algorithm to Find the Least Common Multiples

The most intuitive solution is to check number one by one and then test if it can be divisible by all the numbers from 1 to 20. A better solution is to skip 20 each time.

1
2
3
4
5
6
7
8
9
10
11
12
function checkDivision(n) {
    if (n == 0) return false;
    for (let i = 2; i <= 20; ++ i) {
        if (n % i != 0) return false;
    }
    return true;
}
 
let i = 0;
while (!checkDivision(i)) {
    i += 20;
}
function checkDivision(n) {
    if (n == 0) return false;
    for (let i = 2; i <= 20; ++ i) {
        if (n % i != 0) return false;
    }
    return true;
}

let i = 0;
while (!checkDivision(i)) {
    i += 20;
}

This takes pretty quickly to come up a solution which is 232792560

Greatest Common Divisor and Least Common Multiples

Another solution is to compute the Least Common Multiples of the numbers between 1 to 20. To compute the LCM of two numbers a, b, we need to compute the Greatest Common Divisor or both numbers.

tex_76d14b2469e9f8f27e584f068091608a Smallest Multiple Algorithm using Bruteforce or GCD/LCM algorithms javascript math project euler .

We can use the iterative approach to compute the GCD.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function gcd(a, b) {
    while (b != 0) {
        let c = a % b;
        a = b;
        b = c;
    }
    return a;
}
 
function lcm(a, b) {
    return a * b / gcd(a, b);
}
 
let res = 1;
for (let i = 1; i <= 20; ++ i) {
    res = lcm(res, i);
}
 
console.log(res);
function gcd(a, b) {
    while (b != 0) {
        let c = a % b;
        a = b;
        b = c;
    }
    return a;
}

function lcm(a, b) {
    return a * b / gcd(a, b);
}

let res = 1;
for (let i = 1; i <= 20; ++ i) {
    res = lcm(res, i);
}

console.log(res);

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
吉尼斯宣布“最大份扬州炒饭”纪录无效  包菜有意想不到的防癌养胃保健功效  食药总局公布不合格食品名单蜂蜜上黑榜  板栗养胃健脾是医药学家推崇的补肾果  冬季手脚冰凉者可以多喝“三红”暖身汤  老百姓对于食物中致癌物的认识误区  三类食品是引发癌症(恶性肿瘤)的因素  枸杞虽好但两种人吃了反而对健康有害  4个与大豆营养价值有关的真假说法  早餐第一口吃什么样的食物最养胃 
评论列表
添加评论