C Language Examples - Finding the Greatest Common Divisor of Two Numbers
The user enters two numbers; find the greatest common divisor (GCD) of the two numbers.
Example - Using for and if
#include
<
stdio.h
int
main
(
)
{
int
n1
,
n2
,
i
,
gcd;
printf
(
"
Enter two positive integers, separated by a space:
"
)
;
scanf
(
"
%d %d
"
, &
n1
, &
n2
)
;
for
(
i
=
1
;
i
<=
n1
&&
i
<=
n2
; ++
i
)
{
// Check whether i is the greatest common divisor
if
(
n1
%
i
==
0
&&
n2
%
i
==
0
)
gcd
=
i
;
}
printf
(
"
The greatest common divisor of %d and %d is %d
"
,
n1
,
n2
,
gcd
)
;
return
0
;
}
Running result:
输入两个正整数,以空格分隔: 81 153
81 和 153 的最大公约数是 9
Example - Using while and if
#include
<
stdio.h
int
main
(
)
{
int
n1
,
n2;
printf
(
"
Enter two numbers, separated by a space:
"
)
;
scanf
(
"
%d %d
"
,&
n1
,&
n2
)
;
while
(
n1
!=
n2
)
{
if
(
n1
n2
)
n1
-=
n2
;
else
n2
-=
n1
;
}
printf
(
"
GCD = %d
"
,
n1
)
;
return
0
;
}
Running result:
输入两个数,以空格分隔: 81 153
GCD = 9
Example - Applicable to positive and negative numbers
#include
<
stdio.h
int
main
(
)
{
int
n1
,
n2;
printf
(
"
Enter two numbers, separated by a space:
"
)
;
scanf
(
"
%d %d
"
,&
n1
,&
n2
)
;
// If the input is negative, convert it to a positive number
n1
=
(
n1
0
)
?
n1
: -
n1
;
n2
=
(
n2
0
)
?
n2
: -
n2
;
while
(
n1
!=
n2
)
{
if
(
n1
n2
)
n1
-=
n2
;
else
n2
-=
n1
;
}
printf
(
"
GCD = %d
"
,
n1
)
;
return
0
;
}
Running result:
输入两个数,以空格分隔: 81 -153
GCD = 9
Example - Using recursion
#include
<
stdio.h
int
hcf
(
int
n1
,
int
n2
);
int
main
(
)
{
int
n1
,
n2
;
printf
(
"
Enter two positive integers:
"
)
;
scanf
(
"
%d %d
"
, &
n1
, &
n2
)
;
printf
(
"
The greatest common divisor of %d and %d is %d
"
,
n1
,
n2
,
hcf
(
n1
,
n2
)
)
;
return
0
;
}
int
hcf
(
int
n1
,
int
n2
)
{
if
(
n2
!=
0
)
return
hcf
(
n2
,
n1
%
n2
)
;
else
return
n1
;
}
C Language Examples