zoukankan      html  css  js  c++  java
  • loj #143. 质数判定

    (color{#0066ff}{ 题目描述 })

    判定输入的数是不是质数。

    (color{#0066ff}{输入格式})

    若干行,一行一个数 (x)

    行数不超过 (10^5)

    (color{#0066ff}{输出格式})

    对于输入的每一行,如果 (x) 是质数输出一行 (Y),否则输出一行 (N)

    (color{#0066ff}{输入样例})

    1
    2
    6
    9
    666623333
    

    (color{#0066ff}{输出样例})

    N
    Y
    N
    N
    Y
    

    (color{#0066ff}{数据范围与提示})

    (1≤x≤10^{18})

    (color{#0066ff}{ 题解 })

    就是个Miller Rabbin的板子题

    详解

    #include<bits/stdc++.h>
    #define LL long long
    LL in() {
    	char ch; LL x = 0, f = 1;
    	while(!isdigit(ch = getchar()))(ch == '-') && (f = -f);
    	for(x = ch ^ 48; isdigit(ch = getchar()); x = (x << 1) + (x << 3) + (ch ^ 48));
    	return x * f;
    }
    int prime[] = {2, 3, 5, 7, 11, 61, 24251};
    LL msc(LL x, LL y, LL mod) {
    	x %= mod;
    	y %= mod;
    	LL c = (long double)x / mod * y;
    	LL d = x * y - c * mod;
    	return ((d % mod) + mod) % mod;
    }
    LL ksm(LL x, LL y, LL mod) {
    	LL re = 1LL;
    	while(y) {
    		if(y & 1) re = msc(re, x, mod);
    		x = msc(x, x, mod); 
    		y >>= 1;
    	}
    	return (re + mod) % mod;
    }
    bool judge(LL a, LL p) {
    	LL s = p - 1;
    	while(!(s & 1)) s >>= 1;
    	LL k = ksm(a, s, p);
    	while (s != p - 1 && k != 1 && k != p - 1) k = msc(k, k, p), s <<= 1;
    	return (k == p - 1) || ((s & 1));
    }
    bool judge(LL n) {
    	if(n == 1) return false;
    	for(int i = 0; i < 7; i++) {
    		if(n == prime[i]) return true;
    		if(n % prime[i] == 0) return false;
    		if(!judge(prime[i], n)) return false;
    	}
    	for(int i = 1; i <= 10; i++) if(!judge(2 + rand() % (n - 2), n)) return false;
    	return true;
    }
    
    
    int main() {
    	LL n;
    	while(~scanf("%lld", &n)) printf(judge(n)? "Y
    " : "N
    ");
    	return 0;
    }
    
  • 相关阅读:
    SpringSecurity 框架学习 3
    SpringSecurity 框架学习 项目创建
    nginx 限制ip访问
    nginx 负载均衡,后端服务获取不到域名问题
    Linux 安装 Nginx
    Linux 常用命令
    springcloud 服务追踪
    Hystrix 服务容错
    Scrum立会报告+燃尽图(十二月十日总第四十一次):用户推广
    Final发布:文案+美工展示博客
  • 原文地址:https://www.cnblogs.com/olinr/p/10305930.html
Copyright © 2011-2022 走看看