Java用辗转相除法求两个整数的最大公约数
按照欧几里得(Euclid)的辗转相除法,gcd(a,b)有以下的性质:
- gcd(a,b)=gcd(b,a)
- gcd(a,b)=gcd(-a,b)
- gcd(a,0)=|a|
- gcd(a,b)=gcd(b,a%b),0<=a%b<b
输入:
12
18
package com;
import java.io.*;
public class app4_9 {
public static void main(String[] args)throws IOException
{
int a,b,k;
String str1,str2;
BufferedReader buf;
buf=new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入第一个数a=");
str1=buf.readLine();
a=Integer.parseInt(str1);
System.out.println("请输入第二个数b=");
str2=buf.readLine();
b=Integer.parseInt(str2);
System.out.print("gcd("+a+","+b+")=");
do{
k=a%b;
a=b;
b=k;
}while(k!=0);
System.out.println(a);
}
}