Go语言版本
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package
main
import
"fmt"
func main() {
var x, y
int
=
18
,
12
result := gcd(x,y)
fmt.Printf(
"x, y 的最大公约数是 : %d"
,result)
}
func gcd(x,y
int
)
int
{
for
y !=
0
{
x, y = y, x%y
}
return
x
}
|
Pascal语言版
1
2
3
4
5
6
7
8
9
10
|
var
a,b,c:
integer
;
begin
readln(a,b);
c:=a
mod
b;
while
c<>
0
do
begin
a:=b;b:=c;c:=a
mod
b;
end
;
write
(b);
end
.
|
C语言版
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
/*
欧几里德算法:辗转求余
原理: gcd(a,b)=gcd(b,a mod b)
当b为0时,两数的最大公约数即为a
getchar()会接受前一个scanf的回车符
*/
#include<stdio.h>
unsigned
int
Gcd(unsigned
int
M,unsigned
int
N)
{
unsigned
int
Rem;
while
(N > 0)
{
Rem = M % N;
M = N;
N = Rem;
}
return
M;
}
int
main(
void
)
{
int
a,b;
scanf
(
"%d %d"
,&a,&b);
printf
(
"the greatest common factor of %d and %d is "
,a,b);
printf
(
"%d\n"
,Gcd(a,b));
return
0;
}
|
Ruby语言版
1
2
3
4
5
6
7
8
|
#用欧几里得算法计算最大公约数(排版略)
def
gcd(x, y)
if
y ==
0
return
x
else
return
gcd(y, x % y)
end
end
|
C++版
1
2
3
4
5
6
7
8
|
#include <algorithm> // std::swap for c++ before c++11
#include <utility> // std::swap for c++ since c++11
int
gcd(
int
a,
int
b)
{
if
(a < b)
std::swap(a, b);
return
b == 0 ? a : gcd(b, a % b);
}
|
Java版
1
2
3
4
5
6
7
8
9
|
int
divisor(
int
m,
int
n)
{
if
(m % n ==
0
) {
return
n;
}
else
{
return
divisor(n,m % n);
}
}
|
JavaScript版
1
2
3
4
5
6
|
function
gcd(a,b){
var
t;
if
(a<b) t=b,b=a,a=t;
while
(b!=0) t=b,b=a%b,a=t;
return
a;
}
|
Python版
1
2
3
4
5
6
|
def
gcd(a, b):
while
a !
=
0
:
a, b
=
b
%
a, a
return
b
|