1. Topic introduction
Enter a description:
Multiple sets of input, each line enters a positive integer (not greater than 100).
Output description:
For the integer n input in each line, output two lines, the first line, output prime numbers within n (including n), separated by spaces, the second line, output the number of 2s in the array that are cleared to 0
. Newline after each line of output
2. Screening method
The solution process of the screening method is: store positive integers between 2 and n in the array, clear all numbers after 2 that are divisible by 2 in the array, and then clear all numbers that are divisible by 3 after 3 0 , and so on until n.
The numbers in the array that are not 0 are prime numbers.
3. Analysis
First, create an array and place integers from 1 to n in the array.
Secondly, use the mechanism of the screening method to clear all numbers after 2 that are divisible by 2. Here, you need to use double nesting of for,
It means that arr[1] needs to be moduloed by all the values of arr[2] ~arr[n]. If the modulus is equal to 0, set the value of this modulo arr[1] to 0.
4. Code Demonstration
#include <stdio.h>
int main()
{
int n =0;
int count =0;
int arr[1000];
while(scanf("%d",&n)!=EOF)//多组输入
{
for(int i =0;i<n;i++)
{
arr[i]=i+1;//arr[0]内存储数字1
}
arr[0]=0;//把你的1拿出来不然会出错!因为任何数除去1都是整除的
for(int i =1;i<n;i++)
{
if(arr[i]==0)
{
continue;
}
for(int j =i+1;j<n;j++)
//数组中2之后的所有能被2整除的数清0,再把3之后的所有能被3整除的数字清0
{
if(arr[j]!=0)
{
if(arr[j]%arr[i]==0)
{
arr[j]=0;
count++;
}
}
}
}
for(int i=0;i<n;i++)
{
if(arr[i]!=0)
{
printf("%d ",arr[i]);
}
}
printf("\n");
printf("%d",count);
}
return 0;
}