欧几里得算法实现求两正整数的最大公因数

实验目的

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).

调试过程

  1. 调试代码
#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程序设计—谭浩强》

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值