A simple change would show you how fast your program is running, and how much work it has to do. It is easy to print out your status around every 100 iterations.
(Or you could set it to 1000, or 10000 iterations.)
Recognize that you could DOUBLE the speed of your loop in IsPrime
.
After you check 2, you only need to check odd numbers, and could advance with i+=2
instead of i++
.
If you're concerned about speed, why are you spending so much time checking even numbers?
(note that once you start doing only odd-numbers, you also need to change the output test to be a odd number)
You can DOUBLE the speed of the loop in main
as well by also avoiding even numbers there. (again, you have to special-case 2, then use i+=2, starting at 3 to get 3, 5, 7, 9....)
By making the loop in IsPrime
run twice as fast, and making the loop in main
run twice as fast, this should make your program go 4X faster. (if it would've taken an hour before, now it'll be 15 minutes.)
The other big speed improvement you could make is only running the loop to sqrt(num)
, instead of num
Since I hate bringing in floating point functions, such as sqrt
, I instead suggest a close approximation that will stop within 100 iterations of passing the sqrt boundary, and also show status updates regularly.
if (num%2 == 0)
{
flag=0;
return flag;
}
/* Now that we checked 2, we only need to check odd numbers from now on. */
for(i=3;i<num;i+=2)
{
if (i%101 == 0)
{
printf("i is %d out of %d\n", i, num);
if (i*i > num)
{
break; /* If you pass the sqrt boundary, quit. */
}
}
if(num%i==0)
{
flag=0;
break;
}
}
P.S. I put this code into a C# project (minor porting).
Granted, this was now running on a 64-bit OS, with a better compiler and 2.8GHz CPU.
It ran in less than 20 seconds.