Math: GCD LCM

发布时间 2023-05-29 19:25:58作者: ascertain

 

What is the GCD?

In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that is a divisor of both numbers. For example, the GCD of 8 and 12 is 4.

The greatest common divisor is also known as the greatest common factor (gcf), highest common factor (hcf), greatest common measure (gcm), or highest common divisor.

 

辗转相除法 method of successive division

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
//#include <sys/wait.h>

int main() {
    int m, n, r;
    scanf("%d %d", &m, &n);
    if (m > n) {
        m = n ^ m;
        n = m ^ n;
        m = m ^ n;
    }
    while (m) {
        r = n % m;
        n = m;
        m = r;
    }
    printf("greatest common divisor %d\n", n);
}

 

Recursion

package org.example;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int m = scanner.nextInt();
        int n = scanner.nextInt();
        System.out.println(gcd(m, n));
    }

    public static int gcd(int m, int n) {
        if (m > n) {
            m = n ^ m;
            n = m ^ n;
            m = m ^ n;
        }
        int t = n % m;
        if (t == 0)
            return m;
        else
            return gcd(m, t);
    }
}

 

更相减损法

def gcd(m: int, n: int) -> int:
    if m > n:
        m, n = n, m
    while n - m != m:
        t = n - m
        m, n = m, t if m < t else (t, m)
    return m

 

 

LCM

The abbreviation LCM stands for 'Least Common Multiple' or the Lowest Common Multiple. The least common multiple (LCM) of two numbers is the lowest possible number that can be divisible by both numbers. It can be calculated for two or more numbers as well. There are different methods to find the LCM of a given set of numbers. One of the quickest ways to find the LCM of two numbers is to use the prime factorization of each number and then the product of the highest powers of the common prime factors will be the LCM of those numbers. Let us learn how to find the lowest common multiples of numbers on this page.

function lcm(m, n) {
    if(m > n) {
        [m, n] = [n, m]
    }
    let t = n
    while(!(t % m === 0 && t % n === 0)) {
        t += m
        console.log(`\x1b[7m${t}\x1b[0m`)

    }
    return t
}

console.log(`\x1b[7mLeast common multiple: ${lcm(2, 3)}\x1b[0m`)