-1

Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers! Input

The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space. Output

For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

Can anyone help me optimize my code as it is showing Time limit exceeded even after i am using sieve. Here is the link to the problem https://www.spoj.com/problems/PRIME1/ Here is my code:

#include <iostream>
#include <math.h>
using namespace std;

int is_prime(int m)
{
    int i,c=0;
    for(i=2;i<=sqrt(m);i++)
    {
        if(m%i==0)
        c++;
    }

    if(c==0)
    return 1;
    else
    return 0;
}
int main()
{
    int n,m,i,j,k,num;
    cin>>num;
    for(i=1;i<=num;i++)
    {
      cin>>m>>n;


      int a[n];
      for(j=0;j<=n;j++)
      a[j]=1;
      for(j=m;j<sqrt(n);j++)
      {
         if(is_prime(j)==1)
         {

            for(k=j*j;k<=n;k=k+j)
            {
                a[k]=0;
            }
         }
      }
      for(j=m;j<=n;j++)
      {
            if(a[j]==1)
            cout<<j<<endl;


      }
    cout<<endl;


   }

    enter code here
    return 0;
}
Kivtas
  • 27
  • 1
  • 6

1 Answers1

2

Your code has few issues:

  • You cannot create 10^9 (int a[n] ) array in given time constraint!

  • The nested for loops are taking too long almost O(sqrt(n-m)^2)

To optimise use https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes and https://www.geeksforgeeks.org/segmented-sieve/

Ishpreet
  • 5,230
  • 2
  • 19
  • 35