Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

大家是用什么办法判断素数的?筛选法空间不够吧

Posted by qiqilrq at 2007-02-06 10:32:28 on Problem 2689
我的总是TLE。。。

#include <iostream>
#define MS 40000000

using namespace std;
bool prime[MS];
inline bool isprime(int n)
{
	if(n<MS) return prime[n];
    for(int i=2; i*i<= n; i++) if(prime[i]) //i is a prime
    {
        if(n%i == 0){
            return false;
        }
    }
    return true;
}

main()
{
  int i,j;
  prime[1]=0;
  for(i=2; i<MS; i++)
	  prime[i] = 1;
  for(i=2;i<MS/2;i++)
  {
    if(prime[i])
    {
      for(j=i*2;j<MS;j=j+i)
		  prime[j]=0;
    }
  }
  
  int L,U;
  int c1,c2,d1,d2,lp;
  int cdis,ddis;
  
  while(cin>>L>>U)
  {
      int cnt=0;
      cdis=1000000,ddis=0;lp=-1;                      
      for(i=L; i<=U; i++) if(isprime(i))
      {
          if(cnt++ %2 == 0) i=(i+U)/2;
          if(lp>0)                    //last prime is not void
          {
              if(i-lp < cdis){
                  cdis=i-lp;
                  c1 = lp; c2 = i;
              }
              if(i-lp > ddis){
                  ddis=i-lp;
                  d1 = lp; d2 = i;
              }
          }
          lp = i;
      }
      if(cdis == 1000000 || ddis == 0) 
          cout<<"There are no adjacent primes."<<endl;
      else
          cout<<c1<<","<<c2<<" are closest, "
              <<d1<<","<<d2<<"are most distant."<<endl;                     
  }
  return 0;
}


Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator