跳到正文

题解

题解:P13016 [GESP202506 六级] 最大因数

easy42约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年6月30日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 2 分钟
获赞
2
题目
P13016

版本

  1. v1当前

这不很好想吗,哪里有黄啊。

首先,题目显然叫我们求出两点之间的最近公共祖先,且要求出 a,ba,b 与它们之间祖先的长度,使用暴力跳祖先的方法,找到祖先则需要预处理出 109\sqrt{10^9} 内的质数,可以把时间复杂度做到 O(q×primes×ans)O(q \times primes \times ans),其中 primesprimes 是 109\sqrt{10^9} 内的质数个数。

时间复杂度与 ansans 有关,但是答案实际上非常小,应该是在 a=2xa=2^x 和 b=3yb=3^y 时取到最大,不会超过 3030。

然后第二个是 109\sqrt{10^9} 内的质数个数,这个也大约在几千左右。

于是就做完了。

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
int q;
int f[100005],cnt;
int check(int x){
	if(x<=1) return 0;
	for(int i=2;i<=sqrt(x);i++){
		if(x%i==0) return 0;
	}
	return 1;
}
signed main(){
	cin>>q;
	for(int i=2;i<=sqrt(1e9);i++){
		if(check(i)) f[++cnt]=i;
	}
	while(q--){
		int a,b;
		cin>>a>>b;
		int ans=0;
		while(1){
			if(a==b) break;
			if(a>b){
				if(check(a)){
					a=1;
				}
				for(int i=1;i<=cnt;i++){
					if(a%f[i]==0){
						a=a/f[i];
						break;
					}
				}
			}
			else{
				if(check(b)){
					b=1;
				}
				for(int i=1;i<=cnt;i++){
					if(b%f[i]==0){
						b=b/f[i];
						break;
					}
				}				
			}
			ans++;
		}
		cout<<ans<<endl;
	}
	return 0;
}
原文