Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store.
Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.
Jzzhu wonders how to get the maximum possible number of groups. Can you help him?
A single integer n (1 ≤ n ≤ 105), the number of the apples.
The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group.
If there are several optimal answers you can print any of them.
6
2 6 3 2 4
9
3 9 3 2 4 6 8
2
0
题意:
给出n(1 <= n <= 10^5)个数,从1到n,求出不互质的数对最多有多少对(每个数只能用一次,且最大公约数大于1)并将这几对数输出。
题解:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<stack>
#include<set>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define fi first
#define se second
#define mp make_pair
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
const int inf=0x3fffffff;
const ll mod=1000000007;
const int maxn=1e5+100;
int prime[maxn];
int vis[maxn];
void getPrim()
{
for(int i=2;i<maxn;i++)
{
if(!prime[i])
{
prime[++prime[0]] = i;
}
for(int j=1;(j<=prime[0])&&(i*prime[j]<maxn);j++)
{
prime[prime[j]*i] = 1;
if(i%prime[j]==0) break;
}
}
}
int n;
VI V;
vector<PII> ans;
int main()
{
getPrim();
while(~scanf("%d",&n))
{
memset(vis,0,sizeof(vis));
V.clear();
ans.clear();
vis[1]=1;
int j=1;
while(prime[j]*2<=n) j++;
while(prime[j]<=n&&j<=prime[0]) vis[prime[j]]=1,j++;
int res=0;
for(int j=2;prime[j]*2<=n;j++)
{
int num=0;
int i=prime[j];
while(i<=n)
{
if(!vis[i]) num++;
i+=prime[j];
}
if(num&1)
{
vis[prime[j]*2]=1;
V.pb(prime[j]*2);
num--;
}
if(num>=2)
{
int cnt=1;
int p=prime[j];
int t=prime[j];
while(p<=n)
{
p+=prime[j];
if(!vis[p])
{
cnt++;
if(cnt&1) t=p;
else
{
ans.pb(make_pair(t,p));
vis[t]=vis[p]=1;
}
}
}
}
res+=num/2;
}
for(int i=2;i<=n;i+=2)
if(!vis[i]) V.pb(i);
res+=V.size()/2;
printf("%d\n",res);
for(int i=0;i<ans.size();i++)
printf("%d %d\n",ans[i].first,ans[i].second);
for(int i=0;i+1<V.size();i+=2)
printf("%d %d\n",V[i],V[i+1]);
}
return 0;
}