GCD
辗转相除法求最大公因数
对于两个数a,b来说,如果a > b,有 a = q*b + r,则(a, b)=(b, r);一直重复下去知道r等于0,则最后一个不为0的r就是(a, b)
package gcdAndLCM;
import java.util.Scanner;
public class GCD {static int Gcd (int a, int b ) {int r = 0;if (b > a) {int t = a;a = b;b = t;}else {r = a % b;while (r != 0) {a = b;b = r;r = a % b;}}return b;}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("输入整数a和b:");int a = scanner.nextInt();int b = scanner.nextInt();scanner.close();int gcd = Gcd(a, b);System.out.println("最大公因数是:");System.out.println(gcd);}
}
LCM
求出GCD,用 a*b / GCD。