练习题

:::warning

pow(x, n)

50. Pow(x, n) (剑指 Offer 16. 数值的整数次方)

  1. var myPow = function(x, n) {
  2. res = 1;
  3. if (n < 0) {
  4. x = 1 / x;
  5. n *= -1;
  6. }
  7. // 考虑到i是小数,故0为分界点
  8. for (let i=n; i!=0; i=Math.floor(i/2)) {
  9. if (i % 2 != 0) {
  10. res *= x;
  11. }
  12. x *= x;
  13. }
  14. return res;
  15. };

最大公约数 gcd

:::success // a < b
function gcd(a: number, b: number): number {
if (a > b) [a, b] = [b, a];
while (a) {
[a, b] = [b % a, a];
}
return b;
}

// a < b
function gcd(a, b) {
return a == 0 ? b : gcd(b % a, a);
} :::

// a < b
function gcd(a, b) {
    if (a == 0) return b;
    return gcd(b % a, a);
}

gcd(2, 6) // 2
gcd(4, 6) // 2
gcd(6, 9) // 3

最小公倍数 lcm

加穷举

将大数依次加1,对得到的数判断其是否可整除两数。

function LCM(n1, n2) {
    let res = n1 < n2 ? n2 : n1;
    while (res % n1 != 0 || res % n2 != 0) {
        res++;
    }
    return res;
}

乘穷举

将大数依次乘N(N为从1开始的自然数),对得到的数判断其是否整除小数。

function LCM(n1, n2) {
    let max = n1 < n2 ? n2 : n1;
    let res = max;
    let min = 1;
    while (res % n1 != 0 || res % n2 != 0) {
        min++;
        res = max * min;
    }
    return res;
}

借助:最大公约数

最小公倍数=两整数的乘积÷最大公约数


function LCM(n1, n2) {
    let res = n1 * n2 / GCD(n1, n2)
    return res;
}

function GCD(n1, n2) {
    if (n1 > n2) {
        [n1, n2] = [n2, n1]
    }
    while (n2 != 0) {
        [n1, n2] = [n2, n1 % n2]
    }
    return n1;
}