题目来源:点击进入【CodeForces 1366D — Two Divisors】
Description
You are given n integers a1,a2,…,an.
For each ai find its two divisors d1>1 and d2>1 such that gcd(d1+d2,ai)=1 (where gcd(a,b) is the greatest common divisor of a and b) or say that there is no such pair.
Input
The first line contains single integer n (1≤n≤5⋅105) — the size of the array a.
The second line contains n integers a1,a2,…,an (2≤ai≤107) — the array a.
Output
To speed up the output, print two lines with n integers in each line.
The i-th integers in the first and second lines should be corresponding divisors d1>1 and d2>1 such that gcd(d1+d2,ai)=1 or −1 and −1 if there is no such pair. If there are multiple answers, print any of them.
Sample Input
10
2 3 4 5 6 7 8 9 10 24
Sample Output
-1 -1 -1 -1 3 -1 -1 -1 2 2
-1 -1 -1 -1 2 -1 -1 -1 5 3
Note
Let’s look at a7=8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a7.
There are other valid pairs of d1 and d2 for a10=24, like (3,4) or (8,3). You can print any of them.
解题思路:
由gcd(x,y)=1;可以推出gcd(x+y,xy)=1。
为什么呢?
我们可以试试反证法:
设这两个数为p ,q。M=p+q N=pq
假设M,N不互质,则有: M=aN或 N=aM (a>1且a为自然数)
当M=aN时,p+q=apq。p= q(ap-1)
p/q=ap-1
因为p,q互质,所以p/q为1或非整数
当p/q=1时,ap=2(不符)
当p/q为非整 数时 ,ap-1为整 数 ,矛盾即M不等于aN
同理可证N不等于aM
所以 M,N互质
那么既然我们知道了这个结论,后续我们只需要维持题目中x*y等于a[i]。那么x+y与a[i]就是互质的。
所以只要a[i]存在两个及以上质因子,p1c1 * p2c2 * …。就让x=p1c1,y=a[i]/(p1c1),就有gcd(x+y,a[i])=1
AC代码(C++):
#include
#include
#include
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl '\n'
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int MAXN = 1e7+5;
bool vis[MAXN];
vector<int> v1,v2(MAXN);
void init(){
vis[0]=vis[1]=true;
for(int i=2;i<MAXN;i++){
if(!vis[i]){
v1.emplace_back(i);
v2[i]=i;
}
for(auto x:v1){
if(i*x*1LL>=MAXN) break;
v2[i*x]=x;
vis[i*x]=true;
if(i%x==0) break;
}
}
}
int main(){
SIS;
init();
int n,v;
cin >> n;
vector<int> a(n,-1),b(n,-1);
for(int i=0;i<n;i++){
cin >> v;
int x=v,y=1,z=v2[v];
while(x%z==0){
x/=z;
y*=z;
}
if(x!=1){
a[i]=x;
b[i]=y;
}
}
for(int i=0;i<n;i++) cout << a[i] << ' ';
cout << endl;
for(int i=0;i<n;i++) cout << b[i] << ' ';
cout << endl;
return 0;
}