TAOCP-1.1_欧几里得算法

1. 算法E(欧几里得算法)

给定两个正整数m和n,求它们的最大公约数,即能够同时整除m和n的最大正整数。

E1. [确保\(m \geq n\)] 如果$ m < n \(, 交换\) m \longleftrightarrow n $。
E2. [求余数] 以n除m并令r为所得余数。(我们将有\(0 \leq r \leq n\)。)
E3. [余数为零?] 若\(r = 0\), 算法结束, n即为答案。
E4. [减少] 置 $m \xleftarrow{} n, n \xleftarrow{} r $,并返回步骤E2

1.1 C实现

#include <stdio.h>
#include <stdint.h>

uint32_t cycles;

int32_t gcd(uint32_t m, uint32_t n)
{
    uint32_t r;

    while ((r = (m % n)) !=0) {
        m = n;
        n = r;
        cycles++;
    }
    return n;
}

int main(void)
{
    uint32_t m, n;
    uint32_t ret;

    printf("Please input 2 positive number(eg: 119 544):\n");
    scanf("%d %d", &m, &n);
    if (m < n)
        ret = gcd(n, m);
    else
        ret = gcd(m, n);

    printf("The gcd of %d and %d is: %d, cycles: %d\n", m, n, ret, cycles);

    return 0;
}

运行结果:

[root@localhost ch1]# make
gcc -Wall -O3 e.c -o e
[root@localhost ch1]# ./e 
Please input 2 positive number(eg: 119 544):
119 544
The gcd of 119 and 544 is: 17, cycles: 3

2. 习题

Q-3.(为了提高效率)改变算法E使得像"\(m \xleftarrow{} n\)"这样平凡的替代运算都加以避免。以算法E的风格来写出这个新算法,称之为算法F。

2. 算法F(欧几里得算法,提高效率)

给定两个正整数m和n,求它们的最大公约数,即能够同时整除m和n的最大正整数。

F1. [求余数] 以n除m并令m为所得余数。(我们将有\(0 \leq m \leq n\)。)
F2. [余数为零?] 若m = 0, 算法结束, n即为答案。
F3. [求余数] 以m除n并令n是余数
F4. [余数为零?] 若n = 0, 算法结束, m即为答案,否则返回F1

#include <stdio.h>
#include <stdint.h>

uint32_t cycles;

int32_t gcd(uint32_t m, uint32_t n)
{

    int flag;

    while(1) {
        cycles++;
        m %= n;
        if (!m) {
            flag = 1;
            break;
        }
        n %= m;
        if (!n) {
            flag = 0;
            break;
        }
    }
    return flag ==1 ? n : m;
}

int main(void)
{
    uint32_t m,  n;
    uint32_t ret;

    printf("Please input 2 positive number(eg: 119 544):\n");
    scanf("%d %d", &m, &n);
    if (m < n)
        ret = gcd(n, m);
    else
        ret = gcd(m, n);

    printf("The gcd of %d and %d is: %d, cycles: %d\n", m, n, ret, cycles);

    return 0;
}

运行结果:

[root@localhost ch1]# make
gcc -Wall -O3 f.c -o f
[root@localhost ch1]# ./f 
Please input 2 positive number(eg: 119 544):
119 544
The gcd of 119 and 544 is: 17, cycles: 2

转载于:https://www.cnblogs.com/jelly-wd/p/4169565.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值