4 / 4
Aug 2019

Hi I am new to C++
can some one tell me how to make my code faster

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

int prime_generator( const int &num1, const int &num2)
{
int ctr=0;
for(int i=num1;i<=num2;i++)
{

	   for(int j=2;j<=sqrt(i);j++)
           {
            if(i%j==0)
              ctr++;
           }
           if(ctr==0&&i!=1)
           {
		   	printf("%d \n",i);
	
		    fflush(stdout);
            
			ctr=0;
           }
           ctr=0;
           
         
   }

return 0;
}

int main() {

int num1=0,num2=0,t=0;
printf("Input:\n");
scanf("%d",&t) ; 

pair<int,int> myvector[10];

for(int j=0;j<t;++j){

scanf("%d %d",&num1,&num2) ;

   `

myvector[j].first=num1 ; //,num2));
myvector[j].second=num2;

}

printf("Output:\n");

for(int j=0;j<t;++j){

	printf("\n");

prime_generator(myvector[j].first,myvector[j].second);

}

return 0;
}

  • created

    Aug '19
  • last reply

    Aug '19
  • 3

    replies

  • 799

    views

  • 2

    users

There’s a couple of obvious improvements here: You don’t need to count the factors, just determine whether there are any, and you only need to test division by one even number if you choose the right one.

Also, I don’t know, but does C/C++ evaluate sqrt(i) on every test of the end condition, or is it smart enough to only evaluate sqrt once?

Sqrt(i) i think is calculated every time loop finishes

can you explain what do you mean by " You don’t need to count the factors, just determine whether there are any, and you only need to test division by one even number if you choose the right one"

How many divisions do you need to do to prove that 100000000 isn’t prime? How many does the code do?

How many divisions do you need to do to prove that 899809343 is prime? How many does the code do?