Split the prime number and, tragedy, write the test data passed, but the time limit exceeded is displayed at the time of submission ..... baidu: It's okay to create a table (solution: Create a table with a prime number of less than 10000)
Two Methods: comparison .. The first is case 2... with more time and less memory .. The first method is much more efficient .. When the table is typed, it is fast...
Case 1:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#define M 10001
void fun(int *prime)
{
int a,i,j,k;
for(i=4;i<=M;i=i+2)
prime[i]=1;
a=sqrt(M);
for(i=3;i<=a;i++)
for(j=i*i;j<=M;j=j+i)
{
if(prime[j]==1)
continue;
prime[j]=1;
}
}
int main( )
{
int prime[M+1],A[M+1],i,j,k=0,m,n,count=0;
memset(prime,0,sizeof(prime));
prime[1]=1;
fun(prime);
for(i=2;i<M;i++)
{
if(prime[i]==0)
{
A[k++]=i;
}
}
while(scanf("%d",&n)!=EOF,n)
{
for(i=0;i<k;i++)
{
m=n-A[i];
if(m>0)
{
if(prime[m]==0&&A[i]!=m)
count++;
}
else
break;
}
printf("%d\n",count/2);
count=0;
}
//system("pause");
return 0;
}
Case 2: When I use the second method, I keep prompting the time limit exceeded... after adding a loop traversal, it's okay ..
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
int n,A[10000],i,j,k=1,t=0;
A[0]=2;
for(i=3;i<=10000;i++)
for(j=2;j<i;j++)
{
if(i%j==0)
break;
else
if((i%j!=0)&&(i==j+1))
{
A[k++]=i;
}
}
while(scanf("%d",&n)!=EOF,n)
{
t=0;
int p;
for(i=0;i<k;i++)
if(A[i]>n)
p=i;
//int p=sqrt(n);
for(k=0;k<=p;k++)
for(j=k+1;j<=p;j++)
if(A[k]+A[j]==n)
t++;
//t=0;
printf("%d",t);
printf("\n");
//k=1;
}
//system("pause");
}
There are two methods to locate all the prime numbers between 2-> N .. One is to use the sieve method, and the other is to check from 2-> N to find the prime number.
For details, see the space of experts .. Http://hi.baidu.com/redraiment/blog/item/948ce93d271164c39e3d620c.html