当前位置:网站首页>求最大公约数与最小公倍数(C语言)
求最大公约数与最小公倍数(C语言)
2022-07-07 08:12:00 【璞玉牧之】
一、题目
写两个函数,分别求两个整数的最大公约数和最小公倍数,用主函数调用这两个函数。两个整数由键盘输入。
二、分析及代码
1.思路
- 最大公约数:两个或多个整数共有约数中最大的一个。利用辗转相除法计算。
- 最小公倍数:两个或多个整数共有倍数中除0外最小的一个。由于两个数的乘积等于这两个数的最大公约数与最小公倍数的积,所以,两个数的最小公倍数等于这两个数的乘积除最大公约数。
- 分析思路:分别定义两个函数,和两个变量a,b。第一个函数用辗转相除法求a,b的最大公约数,假设a>b,令a/b得到余数r,再将b作为被除数,r作为除数,得到余数…直至余数为0。第二个函数利用上述公式可求得两个数的最小公倍数。
2.代码
代码如下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int Greatest_Common_Divisor(int a,int b); //函数声明
int Least_Common_Multiple(int a,int b,int m); //函数声明
int a,b,m,x;
scanf("%d,%d",&a,&b);
m=Greatest_Common_Divisor(a,b);
x=Least_Common_Multiple(a,b,m);
printf("%d和%d的最大公约数是:%d\n",a,b,m);
printf("%d和%d的最小公倍数是:%d\n",a,b,x);
return 0;
}
int Greatest_Common_Divisor(int a,int b) //求最大公约数
{
int temp,r;
if(b>a) //让两个数中较大的数作为被除数
{
temp=a;
a=b;
b=temp;
}
while((r=a%b)!=0)
{
a=b; //使除数b变为被除数a
b=r; //使余数r变为除数b
}
return b;
}
int Least_Common_Multiple(int a,int b,int m) //求最小公倍数
{
return (a*b/m);
}
3.运行结果
边栏推荐
猜你喜欢
ORM -- database addition, deletion, modification and query operation logic
mysql插入数据创建触发器填充uuid字段值
【acwing】789. Range of numbers (binary basis)
VS Code指定扩展安装位置
PDF文档签名指南
基于gis三维可视化技术的智慧城市建设
Weekly recommended short videos: what are the functions of L2 that we often use in daily life?
反卷积通俗详细解析与nn.ConvTranspose2d重要参数解释
STM32中AHB总线_APB2总线_APB1总线这些是什么
Several schemes of building hardware communication technology of Internet of things
随机推荐
Chris Lattner, père de llvm: Pourquoi reconstruire le logiciel d'infrastructure ai
【acwing】786. Number k
【华为机试真题详解】高矮个子排队
[email protected]能帮助我们快速拿到日志对象
IPv4 socket address structure
LLVM之父Chris Lattner:为什么我们要重建AI基础设施软件
The request object parses the request body and request header parameters
Win10 installation vs2015
Google colab loads Google drive (Google drive is used in Google colab)
大整数类实现阶乘
Postman interface test III
Serial communication relay Modbus communication host computer debugging software tool project development case
Postman interface test II
Appx code signing Guide
SQLyog数据库怎么取消自动保存更改
STM32 product introduction
0x0fa23729 (vcruntime140d.dll) (in classes and objects - encapsulation.Exe) exception thrown (resolved)
[second on] [jeecgboot] modify paging parameters
学习记录——高精度加法和乘法
Memory ==c language 1