当前位置:网站首页>求最大公约数与最小公倍数(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.运行结果
边栏推荐
- 关于hzero-resource报错(groovy.lang.MissingPropertyException: No such property: weight for class)
- Programming features of ISP, IAP, ICP, JTAG and SWD
- The method of word automatically generating directory
- Guid主键
- Introduction to energy Router: Architecture and functions for energy Internet
- Use of JSON extractor originals in JMeter
- Video based full link Intelligent Cloud? This article explains in detail what Alibaba cloud video cloud "intelligent media production" is
- Guide de signature du Code Appx
- Embedded background - chip
- 根据设备信息进行页面跳转至移动端页面或者PC端页面
猜你喜欢
01 use function to approximate cosine function (15 points)
Remote meter reading, switching on and off operation command
Serial communication relay Modbus communication host computer debugging software tool project development case
字符串格式化
Guide de signature du Code Appx
【二开】【JeecgBoot】修改分页参数
Some thoughts on the testing work in the process of R & D
Win10 installation vs2015
ORM model -- creation and query of data records
ORM -- query type, association query
随机推荐
Postman interface test VI
Learning records - high precision addition and multiplication
UnityWebRequest基础使用之下载文本、图片、AB包
Appx代码签名指南
China's first electronic audio category "Yamano electronic audio" digital collection is on sale!
C logging method
字符串格式化
学习记录——高精度加法和乘法
Programming features of ISP, IAP, ICP, JTAG and SWD
虚数j的物理意义
Wallys/IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL CONCURRENT
Factorial implementation of large integer classes
【剑指Offer】42. 栈的压入、弹出序列
0x0fa23729 (vcruntime140d.dll) (in classes and objects - encapsulation.Exe) exception thrown (resolved)
Serial communication relay Modbus communication host computer debugging software tool project development case
Postman tutorial - scripting
Study summary of postgraduate entrance examination in October
【ORM框架】
IPv4套接字地址结构
Why is the reflection efficiency low?