HOJ 1015
Problem Description
Nearly prime number is an integer positive number for which it is possible to find such primes P1 and P2 that given number is equal to P1*P2. There is given a sequence on N integer positive numbers, you are to write a program that prints Yes if given number is nearly prime and No otherwise.
Input
Input consists of N+1 numbers. First is positive integer N (1<=N<=50000). Next N numbers followed by N. Each number is not greater than 109. All numbers separated by whitespace(s).
Output
Write a line in output for each number of given sequence. Write Yes if given number is nearly prime and No in other case.
Sample Input
1
6Sample Output
Yes
判断质数的方法已经参考SGU113—— Nearly prime numbers进行优化,但是仍然超时,代码贴在下面。
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
int main()
{
int n;
cin>>n;
int *p=NULL ;
p=(int *)malloc(n*sizeof(int));
if(p==NULL)exit(1);
for(int i=0;i<n;i++){
cin>>p[i];
}
for(int i=0;i<n;i++){
int flag=0;
int *num=NULL ;
num=(int *)malloc(p[i]*sizeof(int));
if(num==NULL)exit(1);
num[2]=0;
for(int l=2; l<sqrt(p[i]*1.0); l++)
{
if(!num[l])for(int j=l*l;j<=sqrt(p[i]*1.0);j+=l)num[j]=1;
}
for(int j=2;j<=sqrt(p[i]*1.0);j++){
if(!num[j]){
if(p[i]%j==0)
if(!(num[p[i]/j])){
flag=1;
cout<<"Yes"<<endl;
break;
}
}
}
if(!flag)cout<<"No"<<endl;
free(num);
}
free(p);
return 0;
}