牛牛与LCM(最小公约数)

链接:https://ac.nowcoder.com/acm/problem/21674
来源:牛客网

牛牛与LCM
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld

题目描述
牛牛最近在学习初等数论,他的数学老师给他出了一道题,他觉得太简单了, 懒得做,于是交给了你,
题目是这样的:
有一堆数,问你能否从中选出若干个数使得这些数的最小公倍数为x
输入描述:
第一行输入一个整数n (1 ≤ n ≤ 50)
第二行输入n个整数ai (1 ≤ ai ≤ 109)
第三行输入一个整数x (2 ≤ x ≤ 109)
输出描述:
如果可以,输出"Possible"
否则输出"Impossible"

示例1
输入
4
2 3 4 5
20
输出
Possible

示例2
输入
3
2 3 4
611
输出
Impossible

示例3
输入
3
2 3 4
12
输出
Possible

示例4
输入
10
1 2 3 4 5 6 7 8 9 10
24
输出
Possible

备注:
子任务1:x <= 1000
子任务2:x <= 1000000
子任务3:无限制

思想

找出x的所有因子,然后求他们的lcm,如果ans%x==0,那说明里面一定有数能够组成(lcm)x;

#include <iostream>
#include<string>
using namespace std;

int gcd(int a, int b) //最大公因子
{
	return b ? gcd(b, a%b) : a;
}
int lcm(int a, int b)
{
	return a / gcd(a, b)*b;//顺序不能写反,不然会爆
}


int main()
{
	int n, a[55], x, ans = 1;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
	}
	cin >> x;
	for (int i = 0; i < n; i++)
	{
		if (x%a[i] == 0)
			ans = lcm(ans, a[i]);

	}
	if (ans%x)
		cout << "Impossible" << endl;
	else
		cout << "Possible" << endl;


	return 0;
}
原文地址:https://www.cnblogs.com/gidear/p/11773644.html