Number theory prime numbers try dividing to judge prime numbers

AcWing 866. Try to divide to determine prime numbers.
Since I am a number theory player in our team, I will be slightly biased towards QWQ in number theory during winter vacation. Record the 2021-01-11 problem and punch card here~
Insert picture description here
AC code:

#include <bits/stdc++.h>

#define ll long long
using namespace std;

bool isPrime(int n) {
    
    
    if( n < 2)
        return false;
    for(int i = 2;i<= n / i;i++)
        if(n % i == 0)
            return false;
    return true;
}

int main() {
    
    
    int n;
    cin >> n;
    while (n--) {
    
    
        ll num;
        cin >> num;
        if(isPrime(num))
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}

Knowledge point description: The
essence of the trial division method to judge prime numbers is actually 根据质数的定义进行暴力枚举, but we can optimize the number of cycles through a property of prime numbers. This property is: 如果d是n的约数,那么 n / d也是 n 的约数,即一个数的约数是成对出现的through this property, trial division can be optimized, and the time complexity is changed from O(n) to O(sqrt(n))

Note: It is
not recommended to write 1: for(int i = 2; i<= sqrt(n); i++)
Reason: the sqrt function must be executed every time the loop is executed, which will be slower

It is not recommended to write 2: for(int i = 2; i * i <= n; i++)
Reason: there may be overflow

Recommended writing! ! !
for(int i = 2; i<= n / i; i++)

Guess you like

Origin blog.csdn.net/qq_45654671/article/details/112500374