C Language Note: seeking screening prime number (for the number of counting to solve a wide range of mass inside)

Original link: http://c.biancheng.net/c/

Problem Description:
Enter an integer n (<= 100), require that all prime numbers between 1 ~ n and outputs, and outputs for each row 5

Analysis:
The number of prime numbers within a required range according to a conventional method is to make the outer loop (loop control variable i), i taken every number in this range; do an inner loop (loop control variable j ), in turn determine the number of i% [2, i-1 ] N is 0, if i in [2, i-1] of this interval has a number of other do, this number is not a prime number i. For the 1 ~ n (user input) will be done once per inner loop number determination, and when n is larger, the number of inner and outer nested loop operation the greater inefficient.

Based on this situation, there has been screening method of application, to avoid duplication and unnecessary cycle, cycle times greatly reduced. Direct look at the code:

#include <stdio.h>
#include <string.h>
#define N 100
int main(void)
{
 int prime[N+1];//prime[i]的值为0表示i在筛子上,值为1表示不在筛子上
 int n;//输入30,求1~n之间的质数(可随意) 
 scanf("%d",&n);
 memset(prime,0,sizeof(prime));//将prime中所有的元素值清0
 prime[1]=1;//默认1不是质数
 for(int i=2;i*i<=n;i++)
 {
  if(prime[i]==0)
  {
   for(int j=2*i;j<=n;j+=i)//筛去i的2倍(i*2,该语句仅执行一次),3倍(j+=i),4倍(j+=i)…,这些数肯定不是质数(因为i除了被1和自身整除外,还能被它自身倍数整除)。 
   {
    prime[j]=1;
   }
  } 
 }
 int t = 0 ;   //统计质数个数,以控制每行输出5个
 for(int i = 1; i <= n; i++) 
 {
  if(prime[i] == 0)   //i是质数,则输出,计数,一行输出5个
  {
   printf("%-2d ", i);
   t++;
   if(t%5 == 0) printf("\n"); //一行已输出5个
  }
 } 
 return 0; 
} 

Output:
Here Insert Picture Description
code above process requires an analog prime numbers between 2 to 30:

  • When i = 2: prime [2] = 0 (i.e., 2 is a prime number, the array subscripts i.e. corresponding to the number we have to operate), prime [4], prime [6], prime [8] ... prime [30] is set to 1. (I.e., in the range of 2 to 30, corresponding to a multiple of the number 2 is not a prime number)

  • When i = 3: Since the prime [3] = 0, the prime [6], prime [9], ... prime [27], prime [30] is set to 1

  • When i = 4: Since the prime [4] = 1, do not continue screening step. Because 4 is not a prime number, because 4 has been filtered out as a multiplication factor of 2

  • When i = 5: Since the prime [5] = 0, the prime [10], prime [15], prime [20], prime [25], prime [30] is set to 1.

  • When i = 6: 6> sqrt (30) algorithm ends (i.e., 6 * 6> 30).

Guess you like

Origin blog.csdn.net/weixin_42124234/article/details/102288780