求两个数之间素数的逻辑错误
Logical error in finding the prime number between two numbers
我正在编写代码来打印两个数字之间的素数,但我的代码给出了错误的输出并在给出后冻结
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";
}
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;
}
我正在编写代码来打印两个数字之间的素数,但我的代码给出了错误的输出并在给出后冻结
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";
}
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;
}