首页 > 其他分享 >Math: GCD greatest common divisor 最大公约数

Math: GCD greatest common divisor 最大公约数

时间:2022-11-30 01:44:06浏览次数:36  
标签:scanner int gcd greatest System common public divisor

 

Loop:

#include <stdio.h>

int main(void) {
    printf("Hello, World!\n");
    int m, n, r;
    scanf("%d%d", &m, &n);
    if (m < n) {
        m = m ^ n;
        n = m ^ n;
        m = m ^ n;
    }
    while (n) {
        r = m % n;
        m = n;
        n = r;
    }
    printf("great common divisor %d\n", m);
    return 0;
}

 

Recursion:

package org.example;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
        Scanner scanner = new Scanner(System.in);
        int a, b;
        a = scanner.nextInt();
        b = scanner.nextInt();
        System.out.println(gcd(a, b));
    }

    public static int gcd(int x, int y) {
        int t;
        if (x < y) {
            x = x ^ y;
            y = x ^ y;
            x = x ^ y;
        }
        if (x % y == 0) {
            return y;
        } else {
            return gcd(y, x % y);
        }
    }
}

 

标签:scanner,int,gcd,greatest,System,common,public,divisor
From: https://www.cnblogs.com/dissipate/p/16937249.html

相关文章