[Problem solution] Filter prime numbers within N

Title description:
Use simple prime number screening method to find prime numbers within N.

Input:
N

Output
2~N prime numbers

Sample input
30

Sample output
2
3
5
7
11
13
17
19
23
29

Solution:
First, explain what prime numbers are?
A prime number generally refers to a prime number, and a prime number refers to a natural number that has no other factors except 1 and itself among the natural numbers greater than 1.
In the general field, for a positive integer n, if it is divided by all the integers between 2 and the root of n, it is not evenly divisible, then n is a prime number.
A prime number is greater than or equal to 2, and cannot be divisible by itself and a number other than 1.
Note that 1 cannot be considered a prime number in the strict sense.

For example, if you want to rent a room in a hotel, and each room has a different unit price, our strategy is to not have any leftover money. And only rent the same type of house, and rent as many houses as possible.
There are several types of rooms here: 2, 3, 4...n blocks each.
When you have 10 yuan, the best choice is to rent the "2 yuan" room, because you can rent 5 rooms. If you can rent more than one room, then this number is a composite number.
But when you have 11 yuan, the best option is to rent the "11 yuan" room, but you can only rent one room. Then this number is prime.

Code:


#include <stdio.h>
#include <stdlib.h>

int main(){
    
    
    //接收数据
    int n, judge;
    scanf("%d", &n);    //接收输入

    for(int i = 2; i <= n; i++){
    
        //外循环,循环2~n的每一个数
        judge = 1;  //judge = 1时,代表这个数是素数

        //内循环,用来循环2~n 的开方之间的每一个数
        for(int j = 2; j * j <= i; j++){
    
    
            if(i % j == 0){
    
     //判断i 是否有其他的因数
                judge = 0;  //如果有的话,条件为假,退出内循环
                break;
            }
        }
        //如果judge 依旧为1的话,代表i是素数
        if(judge) printf("%d\n", i);
    }


    return 0;
};

Guess you like

Origin blog.csdn.net/weixin_43776724/article/details/105673097