如何快速求一个序列的gcd和lcm

背景:
教授在打某道关于序列gcd与lcm的题,但是看不懂题解,于是决定打表找规律;然而自己又懒得算数,于是写了个程序。
使用说明:
输入格式:n str a1 a2 ... an\(n\) 为序列长度;str为操作种类,只有GCDLCM\(a\) 为序列,其中所有元素都必须是自然数。
如果输入不合法,程序会中断计算并返回错误信息;否则会直接输出答案。
代码:

#include<bits/stdc++.h>
using namespace std;
#define il inline
#define ri register int
#define inf 0x3f3f3f3f
char c[4];
long long a,b;
unsigned long long ans;
il long long gcd(long long x,long long y)
{
	if(!x&&!y)
	{
		return 1;
	}
	if(!x)
	{
		return y;
	}
	if(!y)
	{
		return x;
	}
	while(1)
	{
		if(x<y)
		{
			swap(x,y);
		}
		x%=y;
		if(!x)
		{
			return y;
		}
	}
}
int main()
{
	while(1)
	{
		scanf("%s",c);
		if(!strcmp(c,"GCD"))
		{
			scanf("%lld",&a);
			if(a<0)
			{
				puts("ERROR: 序列大小必须是自然数");
				continue;
			}
			ans=0;
			while(a--)
			{
				scanf("%lld",&b);
				if(b<0)
				{
					puts("ERROR: 序列元素必须是自然数");
					break;
				}
				ans=gcd(ans,b);
			}
			if(b>=0)
			{
				printf("%lld\n",ans);
			}
			continue;
		}
		if(!strcmp(c,"LCM"))
		{
			scanf("%lld",&a);
			if(a<0)
			{
				puts("ERROR: 序列大小必须是自然数");
				continue;
			}
			ans=1;
			while(a--)
			{
				scanf("%lld",&b);
				if(b<0)
				{
					puts("ERROR: 序列元素必须是自然数");
					break;
				}
				ans/=gcd(ans,b);
				ans*=b;
			}
			if(b>=0)
			{
				printf("%lld\n",ans);
			}
			continue;
		}
		puts("ERROR: 操作无效");
	}
	return 0;
}
/*
in:n op a_1...a_n
0<=a<=2^32
*/

效果不错。
image

posted @ 2024-09-06 17:42  一位很会的教授er~  阅读(117)  评论(4)    收藏  举报