当前位置:网站首页>求最大公约数与最小公倍数(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.运行结果

边栏推荐
- Why is the reflection efficiency low?
- ArcGIS operation: batch modify attribute table
- This article explains the complex relationship between MCU, arm, muc, DSP, FPGA and embedded system
- JMeter loop controller and CSV data file settings are used together
- request对象对请求体,请求头参数的解析
- ES类和对象、原型
- [email protected]能帮助我们快速拿到日志对象
- 关于hzero-resource报错(groovy.lang.MissingPropertyException: No such property: weight for class)
- [learning notes - Li Hongyi] Gan (generation of confrontation network) full series (I)
- 学习记录——高精度加法和乘法
猜你喜欢

Smart city construction based on GIS 3D visualization technology

串口通讯继电器-modbus通信上位机调试软件工具项目开发案例

反卷积通俗详细解析与nn.ConvTranspose2d重要参数解释

The method of word automatically generating directory

Postman interface test III

Wallys/IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL CONCURRENT

【剑指Offer】42. 栈的压入、弹出序列

ORM -- database addition, deletion, modification and query operation logic

Appx代码签名指南

【ORM框架】
随机推荐
Programming features of ISP, IAP, ICP, JTAG and SWD
Postman interface test VII
MCU与MPU的区别
The request object parses the request body and request header parameters
Deadlock caused by non clustered index in SQL Server
搭建物联网硬件通信技术几种方案
【剑指Offer】42. 栈的压入、弹出序列
request对象对请求体,请求头参数的解析
mysql插入数据创建触发器填充uuid字段值
STM32中AHB总线_APB2总线_APB1总线这些是什么
This article explains the complex relationship between MCU, arm, muc, DSP, FPGA and embedded system
The new activity of "the arrival of twelve constellations and goddesses" was launched
CONDA creates virtual environment offline
Smart city construction based on GIS 3D visualization technology
ES6中的原型对象
STM32 ADC和DMA
JMeter about setting thread group and time
字符串格式化
IPv4套接字地址结构
【学习笔记-李宏毅】GAN(生成对抗网络)全系列(一)