• 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;
    }
    
  • 相关阅读:
    java学习之旅(一):BOS项目使用的技术以及开发环境
    spring手动回滚
    tomcat下配置多端口,多项目
    centos7安装Mysql5.6
    windows phone7 下 Silverlight 异步读取网络图片
    Sencha Touch 本地化存储配置
    LCD1602显示接收的串口通讯字串
    QML 怎么在gridview中用Index定位? 怎么在代理中设置背景?
    89C52定时/计数器
    QML JSON 展示
  • 原文地址:https://www.cnblogs.com/olinr/p/10305930.html
Copyright © 2020-2023  润新知