寻找n个数中k个数的最小公倍数

给定一个数组,其中含有n个整数,还给定一个整数X,可以从n个数中选取任意个数的元素,使这些元素的最小公倍数为X,如果存在则返回Possible,否则返回Impossible.


#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include <string>
#include <string.h>
#include <math.h>
#include <queue>
#include <map>
#include <stack>
#include <vector>
#include <iostream>

using namespace std;
# define LL long long int

class LCMSetEasy
{
public:

	LL gcd(LL a, LL b) { return a%b == 0 ? b : gcd(b,a%b);}
	LL lcm(LL a, LL b) { return a * b / gcd(a, b);}

	string include(vector <int> S, int x)
	{
		int i;
		LL tar = 1;
		for(i = 0; i < S.size(); i++)
		{
			if(x % S[i] == 0)
			{
				tar = lcm(tar, S[i]);
				if(tar > x) return "Impossible";
			}
		}
		if(tar == x) return "Possible";
		return "Impossible";
	}
};

int main()
{
	LCMSetEasy test;
	vector<int> vec;
	vec.push_back(9788);
	vec.push_back(8418);
	vec.push_back(10);
	vec.push_back(35);
	vec.push_back(55);
	vec.push_back(7250);
	cout<<test.include(vec,37683800)<<endl;

	return 0;
}


这里提供两种方法来解决c语言三个整数求最大公约数和最小公倍数的问题: 方法一:根据引用中的方法,可以通过循环计数和判断是否满足条件来求出三个数的最大公约数和最小公倍数。具体代码如下: ``` #include <stdio.h> int main() { int x, y, z, tem, i = 1, num; int k = 1; printf("输入3个数:\n"); scanf("%d %d %d", &x, &y, &z); tem = x; //假设x最小 if (tem > y) //寻找个数的最小值 { tem = y; } if (tem > z) { tem = z; } for (i = 1; i <= tem; i++) //设立循环的次数 { if (x % i == 0 && y % i == 0 && z % i == 0) //最大公约数需要满足的条件 { num = i; } } while (1) //永远成立,无条件循环 { if (k % x == 0 && k % y == 0 && k % z == 0) //判断是否为最小公倍数 break; else k++; } printf("三个数的最大公约数为:%d\n", num); printf("三个数最小公倍数为:%d\n", k); return 0; } ``` 方法二:根据引用中的方法,可以写两个函数分别求两个整数的最大公约数和最小公倍数,然后在主函数中调用这两个函数来求出三个数的最大公约数和最小公倍数。具体代码如下: ``` #include <stdio.h> int hcf(int x, int y) { int z = x % y; while (z) { x = y; y = z; z = x % y; } return y; } int lcd(int a, int b) { int i = 1, result = 0; while ((a * i) % b != 0) { i++; } result = i * a; return result; } int main() { int a, b, c, hcf1, hcf2, hcf3, lcd1, lcd2, lcd3; printf("输入3个数:\n"); scanf("%d %d %d", &a, &b, &c); hcf1 = hcf(a, b); hcf2 = hcf(b, c); hcf3 = hcf(hcf1, hcf2); lcd1 = lcd(a, b); lcd2 = lcd(b, c); lcd3 = lcd(lcd1, lcd2); printf("三个数的最大公约数为:%d\n", hcf3); printf("三个数最小公倍数为:%d\n", lcd3); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值