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/2的素数直接忽略掉。
从不大于n/2的最大素数开始,从大到小找,遇到素数就计算有多少个含有这个素数的合数即(n/p);此外,还要对小的素数的个数进行删除,比如n=30;对于素数7,30/7=4;
7,14,21,28.此时组成两对,然后已经用过21=7*3了,要在3的个数那里减去1也就是4/3=1;
最好用一个bool数组记录那个数已经用过,这样比较方便.
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <algorithm>
#include <ctime>
#include <vector>
#include <cstring>
#include <map>
#include <string>
#include <queue>
//#include <fstream>
using namespace std;
#define LL long long
#define ULL unsigned long long
//#define REP(i,n) for(int i=0;i<n;++i)
#define REP(i,a,b) for(int i=a;i<=b;++i)
#define INFLL (1LL)<<62
#define mset(a) memset(a,0,sizeof a)
#define FR(a) freopen(a,"r",stdin)
#define FW(a) freopen(a,"w",stdout)
#define PI 3.141592654
const LL MOD = 1000000007;
const int maxn=100011;
queue <pair<int,int> > prt;
int a[maxn];
int prime[maxn];
bool b[maxn];
bool bb[maxn];
int n;
int k=0;
void isP()
{
for(int i=2;i<=n/2;++i)
if(!b[i]){
prime[k++]=i;
for(int j=i*2;j<n;j+=i)
b[j]=1;
}
}
int main()
{
mset(a);
cin>>n;
isP();
while (prime[k-1]>n/2) k--;
for (int j=k-1;j>=0;j--)
{
int p=prime[j];
a[p]+=n/p;
for(int i=0;i<=j-1;++i)
if(a[p]/prime[i]) a[prime[i]]-=a[p]/prime[i];
else break;
if(!j) break;
int i;
if(a[p]%2){
a[2]++;
for(i=1;i<n/p;++i)
{
if(i==2) continue;
if(bb[i*p]) continue;
int j;
for(j=i+1;j<=n/p;j++)
{
if(j==2) continue;
if(bb[j*p]) continue;
else {
prt.push(make_pair(i*p,j*p));
bb[i*p]=bb[j*p]=1;
break;}
}
i=j;
}
}
else{
for(i=1;i<n/p;i++)
{
if(bb[i*p]) continue;
int j;
for (j=i+1;j<=n/p;j++)
{
if(bb[j*p]) continue;
else {
prt.push(make_pair(i*p,j*p));
bb[i*p]=bb[j*p]=1;
break;}
}
i=j;
}
}
}
if(n>=4) {prt.push(make_pair(2,4));}
for(int i=3;i<n/2;++i)
{
if(bb[i*2]) continue;
int j;
for(j=i+1;j<=n/2;++j)
if(bb[j*2]) continue;
else {
prt.push(make_pair(i*2,j*2));
break;}
i=j;
}
printf("%d\n",prt.size());
while(!prt.empty())
{
pair<int,int> temp=prt.front();
prt.pop();
printf("%d %d\n",temp.first,temp.second);
}
}