⑴ 用java求兩個整數的最大公約數、最小公倍數
package com.fmzrt;
/**
* 求兩個數的最大公約數和最小公倍數
* @author kele
*
*/
public class GongyueGongbeiShu {
/**
* 求兩個數的最大公約數
* @param m
* @param n
* @return
*/
public static int MaxGys(int m, int n) {
int r;
while(n != 0) {
r = m % n;
m = n;
n = r;
}
return m;
}
/**
* 求兩個數的最小公倍數
* @param m
* @param n
* @return
*/
public static int MinGbs(int m, int n) {
return m * n / MaxGys(m, n);
}
public static void main(String[] args) {
System.out.println("最大公約數 : (36, 12) = " + GongyueGongbeiShu.MaxGys(36, 12));
System.out.println("最小公倍數 : (36, 12) = " + GongyueGongbeiShu.MinGbs(36,12));
}
}
⑵ 用java求兩數的最大公約數和最小公倍數。
import java.util.*;
public class lianxi06 {
public static void main(String[] args) {
int a ,b,m;
Scanner s = new Scanner(System.in);
System.out.print( "鍵入一個整數: ");
a = s.nextInt();
System.out.print( "再鍵入一個整數: ");
b = s.nextInt();
deff cd = new deff();
m = cd.deff(a,b);
int n = a * b / m;
System.out.println("最大公約數: " + m);
System.out.println("最小公倍數: " + n);
}
}
class deff{
public int deff(int x, int y) {
int t;
if(x < y) {
t = x;
x = y;
y = t;
}
while(y != 0) {
if(x == y) return x;
else {
int k = x % y;
x = y;
y = k;
}
}
return x;
}
}