lcm c++_C ++程序查找两个数字的LCM

lcm c++

LCM (least common multiple) of two given numbers m and n is determined by finding the smallest number that is divisible by both the numbers. A simple approach to this problem is to store the maximum of a and b in variable max and check if max is completely divisible by both the numbers, if yes then max is the lcm otherwise increment max by 1.

两个给定数字 m和n的 LCM(最小公倍数)通过找到可被两个数字整除的最小数字来确定。 解决此问题的一种简单方法是将a和b的最大值存储在变量max中,并检查max是否可完全被两个数整除,如果是,则max为lcm,否则将max递增1。

C ++程序使用简单方法查找LCM (C++ program to find LCM using simple approach )

#include <iostream>
using namespace std;

int main()
{
    int m,n,max;

    m=12;
    n=15;
    
    if(m > n) 
		max= m;
	else 
		max = n;	

    while(true)
    {
        if (max % m == 0 && max % n == 0)
        {
            cout << "LCM of "<<m<<" and "<<n<<" = "<< max;
            break;
        }
        else
            max++;
    }
    
    return 0;
}

Output

输出量

LCM of 12 and 15 = 60


使用GCD查找LCM的C ++程序 (C++ program to find LCM using GCD)

We can also use the property of LCM and HCF, we know that the product of two numbers is equal to the product of LCM and HCF.

Therefore LCM of two numbers is given by:

我们还可以使用LCM和HCF的属性,我们知道两个数的乘积等于LCM和HCF的乘积。

因此,两个数字的LCM由下式给出:
    LCM = (n1 * n2) / HCF

We know that, HCF (highest common factor) = GCD (greatest common divisor)

我们知道,HCF(最高公因数)= GCD(最大公因数)

    So, LCM = (n1 * n2) / GCD

#include <iostream> 
using namespace std; 

//function to return gcd of a and b 
int gcd(int a, int b) 
{ 
    if (b == 0) 
        return a; 
    return gcd(b, a % b);  
      
}
 
int main()
{
	int m,n;
	m=12;
	n=15;
	cout<<"LCM of "<<m<<" and "<<n<<" = "<<(m*n)/gcd(m,n)<<endl;
	
	m=7;
	n=100;
	cout<<"LCM of "<<m<<" and "<<n<<" = "<<(m*n)/gcd(m,n);
	
}

Output

输出量

LCM of 12 and 15 = 60
LCM of 7 and 100 = 700


翻译自: https://www.includehelp.com/cpp-programs/find-lcm-of-two-numbers.aspx

lcm c++

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值