EOJ 1094 Prime Judge

2 篇文章 0 订阅

http://acm.cs.ecnu.edu.cn/problem.php?problemid=1094

题意:判断素数。

TLE

#include <iostream>
#include <vector>
using namespace std;
const int maxn = 1000005;
int a[maxn];
vector<int> v;
void init()
{
	a[0] = 1;
	a[1] = 1;
	for(int i=2; i<maxn; i++){
		if(a[i] == 1)continue;
		v.push_back(i);
		for(int j=2; j*i < maxn; j++)a[i*j] = 1;
	}	
}
 
void print()
{
	int s = v.size();
	for(int i=0; i<s; i++){
		cout << v[i] << endl;
	}
}
 
int main()
{
	init();
	long long n;
	while(cin >> n){
		if(n < maxn){
			if(a[n] == 0){
				cout << "YES" << endl;
			}
			else {
				cout << "NO" << endl;
			}
		}
		else {
			for(int i=0; i<v.size() && n != 1; i++){
				if(n % v[i] == 0){
					while(n % v[i] == 0){
						n /= v[i];
					}
				}
				
			}
			if(n == 1){
					cout << "NO" << endl;
				}
				else {
					cout << "YES" << endl;
				}
		}
	}
	//print();
	return 0;	
}

miller rabbin

TLE:做50次太多了,安神说四次都超,三次就过了AC

#include<stdio.h>
#include<stdlib.h>
#include<cmath>
//typedef long long  __int64;
bool witness(__int64 a, __int64 n)
{
    __int64 t,d,x;
    d=1;
    int i=ceil(log(n-1.0)/log(2.0)) - 1;
    for(;i>=0;i--)
    {
        x=d;  d=(d*d)%n;
        if(d==1 && x!=1 && x!=n-1) return true;
        if( ((n-1) & (1<<i)) > 0)d=(d*a)%n;
    }
    return d==1?false: true;
}
 
bool miller_rabin(__int64 n)
{
    if(n==2)    return true;
    if(n==1 || ((n&1)==0))    return false;
    for(int i=0;i<3;i++){ 
        __int64 a=rand()*(n-2)/RAND_MAX +1;
        if(witness(a, n))    return false;
    }
    return true;
}
 
int main()
{
    __int64 a;
    while(scanf("%I64d",&a)!=EOF)
    {
        if(miller_rabin(a))printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值