Before programming, we must first understand the definition of primes: in natural numbers greater than 1, there are no other factors other than 1 and itself.
Therefore, we will first think of a method: Set the 100~200 between the number is I, with I to divide by 2~ (i-1) between each number.
That
#include <stdio.h>
int main ()
{
int I, J;
for (i = n; i <=; i++)
{
for (j = 2; J <= I-1; j + +)
{
if (i%j = = 0)
break;//If you can divide it, jump out of the loop and avoid redundant operations.
}
if (j==i)//The condition represents not divisible.
printf ("%d", I);
}
printf ("\ n");
System ("pause");
return 0;
}
But using this method of programming can make the code cumbersome and the system executing slowly, so we continue to explore whether the code can be optimized.
Here are two ways to optimize:
The first: Since I cannot evenly divide the number larger than I/2, we can set the 3rd variable T, which is used to store the value of I/2.
#include <stdio.h>
int main ()
{
int I, j,t;
for (i = n; i <=; i++)
{
t = I/2;
for (j = 2; J <= T; j + +)
{
if (i%j = = 0)
Break
}
if (j>t)
printf ("%d", I);
}
printf ("\ n");
System ("pause");
return 0;
}
The second type: using T to store the square root of I will optimize the algorithm compared to I/2. But this algorithm needs to introduce the new head function MATH.H, and the new function sqrt () root function.
#include <stdio.h>
#include <math.h>
int main ()
{
int I, j, T;
for (i = n; i <=; i++)
{
t = sqrt (i);//Radical function
for (j = 2; J <= T; j + +)
{
if (i%j = = 0)
Break
}
if (j>t)
printf ("%d", I);
}
printf ("\ n");
System ("pause");
return 0;
}
At this point we are just optimizing the internal loop process, and we can also optimize the external loop.
We all know that the even number between 100~200 is unlikely to be a prime number, so we can artificially initialize I to 101 and +2 for each cycle.
#include <stdio.h>
#include <math.h>
int main ()
{
int I, j, T;
for (i = 101; I <=; i+=2)
{
t = sqrt (i);
for (j = 2; J <= T; j + +)
{
if (i%j = = 0)
Break
}
if (j>t)
printf ("%d", I);
}
printf ("\ n");
System ("pause");
return 0;
}
This optimization will reduce our program calculation by half, which is very effective to improve the efficiency of the program.
Finally, attach the result of the program after running:
Implemented in C: Prints a prime number between 100-200.