a和b的最大公约数
d = gcd(a,b) = gcd(b, a mod b) 当(a mod b) =0时, b极为所求。
同时, d=a*x+b*y(x,y为整数);
代码如下:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
C代码#include<stdio.h>
long gcd(long a, long b, int* x, int* y)
{
int t;
long tmp;
if(b==0)
{
*x=1; *y=0;
return a;
}
else
{
tmp = gcd(b, a % b, x, y);
t=*x; *x=*y; *y=t-(a/b)**y;
return tmp;
}
}
long a,b;
int x,y;
void main()
{
long tmp;
printf("请输入a和b:");
scanf("%ld%ld",&a,&b);
tmp = gcd(a,b,&x,&y);
printf("a和b的最大公约数是:%ld\n", tmp);
printf("%ld=%ld*%d+%ld*%d\n",tmp,a,x,b,y);
}
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Delphi代码program algorithm;
{$APPTYPE CONSOLE}
uses
SysUtils;
{欧几里德算法———求最大公约数}
function gcd(a, b: longint; var x, y: Integer): longint;
var
t: Integer;
begin
if b = 0 then
begin
gcd := a;
x := 1;
y := 0;
end
else
begin
gcd := gcd(b, a mod b, x, y);
t := x;
x := y;
y := t - (a div b) * y;
end;
end;
var
a, b, tmp: longint;
x, y: Integer;
begin
write('请输入a,b:');
readln(a, b);
tmp := gcd(a, b, x, y);
writeln(a, '和', b, '的最大公约数是:', tmp);
writeln(tmp, '=', a, '*', x, '+', b, '*', y);
readln;
end.
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Java代码package com.number;
import java.util.Scanner;
public class MainUnit {
int x,y;
public static void main(String[] args) {
MainUnit mm= new MainUnit();
System.out.println("请输入a和b:");
Scanner sc=new Scanner(System.in);
long a=sc.nextLong();
long b=sc.nextLong();
long tmp=mm.gcd(a,b);
System.out.println(a+"和"+b+"的最大公约数是:"+ tmp);
System.out.println(tmp+"="+a+"*"+mm.x+"+"+b+"*"+mm.y);
}
public long gcd(long a, long b)
{
long tmp;
if (b==0) {
x=1; y=0;
return a;
}
else {
tmp= gcd(b, a%b);
int t=x;
x=y;
y=t-(int)(a/b)*y;
return tmp;
}
}
}