Judge whether a number is prime
Posted by morphy@6deex on Tue, 24 Dec 2019 19:39:08 +0100
Determine whether a number is prime.
When the number is large, it is not reliable to use simple methods. There are many ways to judge prime numbers;
1: There is no more about simple violence;
2: That is to simplify on the basis of violence, violence sqrt(n) is OK;
3: Is the more commonly used algorithm eratosthene screening method;
But when we meet a larger number, these three methods are not enough to solve the problem. So we can combine the second method and the third method to judge
The code is as follows:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#define pi acos(-1)
#define For(i, a, b) for(int (i) = (a); (i) <= (b); (i) ++)
#define Bor(i, a, b) for(int (i) = (b); (i) >= (a); (i) --)
using namespace std;
typedef long long ll;
const int maxn = 50000 + 10;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-10;
const ll mod = 1e9 + 7;
inline int read(){
int ret=0,f=0;char ch=getchar();
while(ch>'9'||ch<'0') f^=ch=='-',ch=getchar();
while(ch<='9'&&ch>='0') ret=ret*10+ch-'0',ch=getchar();
return f?-ret:ret;
}
bool isprime[maxn];
int prime[maxn],nprime;
void doprime(){
ll i, j;
nprime = 0;
memset(isprime, true, sizeof(isprime));
isprime[1] = 0;
for(i = 2; i <= maxn; i++){
if(isprime[i]){
prime[++nprime] = i;
for(j = i + i; j < maxn; j += i){
isprime[j] = false;
}
}
}
}
bool isp(int n){
int i, k = (int)sqrt(double(n));
for(i = 1; prime[i] <= k; i ++){
if(n % prime[i] == 0)return false;
}
return true;
}
int main(){
doprime();
ll n;
while(scanf("%lld",&n)){
if(n == 1){
printf("NO\n");
continue;
}
if(isp(n))printf("YES\n");
else printf("NO\n");
}
return 0;
}
I'm summarizing and recording some of the problems I've done.