查找两个数字之间的素数时的逻辑错误

时间:2015-08-02 19:22:15

标签: c++ computer-science primes number-theory

我正在编写代码来在两个数字之间打印素数,但我的代码输出错误,并在给出之后冻结
http://www.spoj.com/problems/PRIME1/

#include<iostream>
#include<cmath>
using namespace std;   
int main()
 {
 int t,j,i=0;
 cin>>t;
 int m,n;
 int primes[i];
 while(t--)  //t is the number of test-cases
  {
  cin>>m >>n;   //m and n are the numbers between which prime numbers have to be calculated
    for(i=0;i<=n;i++) //Using Sieve algorithm
      primes[i]=1;
    primes[0]=0;
    primes[1]=0;
    for(i=2;i<=sqrt(n);i++)
    {
        if(primes[i]==1)
        {
            for(j=2;i*j<=n;j++)
            primes[i*j]=0;
        }
    }
   for(i=2;i<=n;i++)
   {
       if(i>=m&&primes[i]==1)//Printing numbers which are greater than m
        cout<<i<<"\n";
   }
   cout<<"\n";
  }

1 个答案:

答案 0 :(得分:0)

int primes[i];

不是合法的C ++。从i == 0起,它甚至不能使用C ++。

显然,你需要分配一个足够大的数组。

int *primes;
while(t--)  //t is the number of test-cases
  {
  cin>>m >>n;   //m and n are the numbers between which prime numbers have to be calculated
  primes = new int[n+1]; // allocate a big enough array
  ...
  delete[] primes;
}