寻找最小公倍数高效算法

理论基础

理论一:

  • 两个数的最小公倍数等于这两个数的乘积除以它们的最大公约数(GCD)。
  • 即 LCM(a, b) = |a*b| / GCD(a, b)

例如,求12和18的最小公倍数:

  • GCD(12, 18) = 6
  • LCM(12, 18) = |12*18| / 6 = 216 / 6 = 36
    理论二:

辗转相除法,也称为欧几里得算法,是一种用于寻找两个整数最大公约数的高效算法。

假设我们想要找到81和153的最大公约数。

  1. 153除以81,商为1,余数为72。
  2. 然后用81除以72,商为1,余数为9。
  3. 再用72除以9,商为8,余数为0。

这时余数为0,所以在上一步中,9就是153和81的最大公约数。

cpp 复制代码
//C++代码实现
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int getGCD(int did, int div) {	//辗转相除法
	while(did % div) {
		int red = did % div;
		did = div;
		div = red;
	}
	return div;
}

int main(int argc, char** argv) {
	srand(time(0));
	int res1 = rand()%1001;
	int res2 = rand()%801;
	
	int gcd = getGCD(res1, res2);
	cout<<"The GCD is "<<gcd<<endl;
	
	int lcm = res1 * res2 / gcd;
	cout<<"The LCM of "<<res1<<" and "<<res2<<" is "<<lcm;
	return 0;
}
相关推荐
smj2302_796826521 天前
解决leetcode第3768题.固定长度子数组中的最小逆序对数目
python·算法·leetcode
cynicme1 天前
力扣3531——统计被覆盖的建筑
算法·leetcode
core5121 天前
深度解析DeepSeek-R1中GRPO强化学习算法
人工智能·算法·机器学习·deepseek·grpo
mit6.8241 天前
计数if|
算法
a伊雪1 天前
c++ 引用参数
c++·算法
Data_agent1 天前
1688获得1688店铺列表API,python请求示例
开发语言·python·算法
2301_764441331 天前
使用python构建的应急物资代储博弈模型
开发语言·python·算法
hetao17338371 天前
2025-12-11 hetao1733837的刷题笔记
c++·笔记·算法
Xの哲學1 天前
Linux电源管理深度剖析
linux·服务器·算法·架构·边缘计算
小飞Coding1 天前
一文讲透 TF-IDF:如何用一个向量“代表”一篇文章?
算法