C 练习实例16 - 最大公约数和最小公倍数

C 语言教程 · 2019-02-21 15:57:19

题目:输入两个正整数m和n,求其最大公约数和最小公倍数。

程序分析:

(1)最小公倍数=输入的两个数之积除于它们的最大公约数,关键是求出最大公约数;

(2)求最大公约数用辗转相除法(又名欧几里德算法)

1)证明:设c是a和b的最大公约数,记为c=gcd(a,b),a>=b,
令r=a mod b
设a=kc,b=jc,则k,j互素,否则c不是最大公约数
据上,r=a-mb=kc-mjc=(k-mj)c
可知r也是c的倍数,且k-mj与j互素,否则与前述k,j互素矛盾,
由此可知,b与r的最大公约数也是c,即gcd(a,b)=gcd(b,a mod b),得证。

2)算法描述:

第一步:a ÷ b,令r为所得余数(0≤r 第二步:互换:置 a←b,b←r,并返回第一步。

实例

// Created by www.codercto.com on 15/11/9. // Copyright © 2015年 码农教程. All rights reserved. // #include<stdio.h> int main() { int a,b,t,r; printf("请输入两个数字:\n"); scanf("%d %d",&a,&b); if(a<b) {t=b;b=a;a=t;} r=a%b; int n=a*b; while(r!=0) { a=b; b=r; r=a%b; } printf("这两个数的最大公约数是%d,最小公倍数是%d\n",b,n/b); return 0; }

以上实例输出结果为:

请输入两个数字:
12 26
这两个数的最大公约数是2,最小公倍数是156

点击查看所有 C 语言教程 文章: https://www.codercto.com/courses/l/17.html

查看所有标签

Agile Web Application Development with Yii 1.1 and PHP5

Agile Web Application Development with Yii 1.1 and PHP5

Jeffrey Winesett / Packt Publishing / 2010-08-27

In order to understand the framework in the context of a real-world application, we need to build something that will more closely resemble the types of applications web developers actually have to bu......一起来看看 《Agile Web Application Development with Yii 1.1 and PHP5》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

MD5 加密
MD5 加密

MD5 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试