实验目的
Accomplish the Euclidean algorithm to calculate the greatest common divisor of tow positive integer a and b on the computer.
实验内容
Using c-language to accomplish the Euclidean algorithm.
使用环境
Win 11 & visual studio code 2022
算法介绍
Algorithm: Euclidean algorithm
Input: tow positive integer a and b
Output: the GCD and LCM of a and b
Begin
Step 1: sort a and b from large to small
Step 2: find remainder from two numbers
Step 3: find remainder with the smaller one, until the remainder equal 0
End : output the previous remainder, the number is GCD(a,b).
调试过程
- 调试代码
#include <stdio.h>
void max(int x,int y);
int GCD(int x,int y);
int main()
{
int x, y;
printf("input positive integer x,y:");
scanf("%d,%d,", &x, &y);
getchar();
max(x,y); //对两整数从大到小排序
GCD(x,y); //输出最大公因数和最小公倍数
getchar();
return 0;
}
void max(int x,int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
int GCD(int x,int y)
{
int p, r;
p = x * y;
while (y != 0)
{
r = x % y;
x = y;
y = r;
}
printf("GCD(x,y)=%d\n", x);
printf("LMD(x,y)=%d\n", p / x);
return x;
}
总结
The Euclidean algorithm should be realized by loop and “triangle transform”. Calculate LCM(a, b) by theorem: GCD(a, b)*LCM(a, b) = a * b.
参考文献
《C prime plus》《C程序设计—谭浩强》