当前位置:网站首页>C语言每日一练——Day02:求最小公倍数(3种方法)
C语言每日一练——Day02:求最小公倍数(3种方法)
2022-08-11 06:06:00 【小牛要翻身】
一、什么是公倍数?
通过直观的理解,我们很容易知道,所谓的公倍数就是两个数共有的倍数;那么最小公倍数,就是他们共有的倍数中最小的那个数。比如2和4的最小公倍数是4,15和20的最小公倍数是60……
二、求解两个数的最小公倍数
1、枚举法
思路: 已知两个数的最小公倍数大于等于两个数的最大值,所以可以先求出两个数的较大值
max
,用max分别试除两个数,如果能整除,max即为两个数的最小公倍数;不能整除,让max=max+1
直到找到最小公倍数为止。
️如:求12和8的最小公倍数
- 先求较大值12,12不是两个数的最小公倍数
- 12+1=13,13+1=14……,23+1=24可以整除这两个数
- 所以24是最小公倍数
代码展示:
//枚举法
#include<stdio.h>
int main()
{
int x = 0;
int y = 0;
scanf("%d %d",&x,&y);
int max = (x > y ? x : y);//取最大值
while (max%x != 0 || max%y!= 0)//如果不能同时整除
{
max++;//每次增加1
}
printf("%d",max);
return 0;
}
2、公式法
思路: 两个数的最小公倍数数等于两个数的乘积除以两个数的最大公约数。即:x,y的最小公倍数
min(公倍数)=x*y÷max(公约数)
️如:求12和8的最小公倍数
- 求得12和8的最大公约数是4
- 即12和8的最小公倍数是12×8÷4=24
代码展示:
//公式法:
#include<stdio.h>
int main()
{
int x = 0;
int y = 0;
scanf("%d %d",&x,&y);
int z = x * y;//将两个数的乘积存起来方便后续使用
//求最大公约数
while (x % y != 0)
{
int tmp = x % y;
x = y;
y = tmp;
}
int min = z / y;//最小公倍数
printf("%d",min);
return 0;
}
3、迭乘法
思路: 已知两个数的公倍数一定与这两个数存在倍数关系,那么求解最小公倍数我们就可以将其中一个数依次扩大
1
倍、2
倍、3
倍……直到出现第一个扩大n
倍的数可以同时整除这两个数,这个数就是最小公倍数。
️如:求12和8的最小公倍数
- 12×1=12,12不是8的倍数
- 12×2=24,24是8的倍数
- 24是12和8的最小公倍数
代码展示:
//迭乘法
#include<stdio.h>
int main()
{
int x = 0;
int y = 0;
scanf("%d %d",&x,&y);
int i = 1;
while (x * i %y != 0)
{
i++;
}
printf("%d",x*i);
return 0;
}
总结
上述三种方法中:
- 迭乘法效率最高,建议使用。
- 枚举法效率最低,不推荐使用。
边栏推荐
- Unity游戏排行榜的制作与优化
- HCIP Republish/Routing Policy Experiment
- mmdetection的安装和训练、测试didi数据集的步骤(含结果)
- 1688 product interface
- When MySQL uses GROUP BY to group the query, the SELECT query field contains non-grouping fields
- Strongly recommend an easy-to-use API interface
- HCIA experiment
- 抖音分享口令url API工具
- unable to extend table xxx by 1024 in tablespace xxxx
- 使用Keras构建GAN,以Mnist为例
猜你喜欢
什么是Inductive learning和Transductive learning
Taobao API common interface and acquisition method
My meeting of the OA project (meeting seating & review)
姿态解算-陀螺仪+欧拉法
如何选择专业、安全、高性能的远程控制软件
强烈推荐一款好用的API接口
My approval of OA project (inquiry & meeting signature)
淘宝API接口参考
Amazon Get AMAZON Product Details API Return Value Description
Get Pinduoduo product information operation details
随机推荐
Douyin API interface
maxwell concept
矩阵分析——Jordan标准形
每日sql:求好友申请通过率
Concurrent programming in eight-part essay
Daily sql: request for friend application pass rate
Unity底层是如何处理C#的
Taobao sku API interface (PHP example)
redis + lua实现分布式接口限流实现方案
淘宝sku API 接口(PHP示例)
每日sql -用户两天留存率
Internet phone software or consolidation of attack must be "free" calls security clearance
ROS 服务通信理论模型
unable to extend table xxx by 1024 in tablespace xxxx
HCIA experiment
Unity3D 学习路线?
一张图了解JVM八大原子操作
Daily sql-employee bonus filtering and answer rate ranking first
一个小时快速熟悉MySQL基本用法
快速了解集成学习