素数的Miller_Rabbin测试

本文介绍了一种用于检测强伪素数的算法,并通过C++实现了一个具体的例子。该算法利用了模幂运算和Miller-Rabin素性测试,能够有效地判断小于等于50万的数是否为素数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一个以2为底的强伪素数为2047。第一个以2和3为底的强伪素数则大到1 373 653。

  微笑




</pre><pre name="code" class="cpp">#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <queue>
#include <map>
#include <set>
#include <vector>
using namespace std;
const __int64 maxn = 500005;
__int64 powe_m(__int64 a,__int64 b,__int64 c)
{
	__int64 ans=1; 
	__int64 tmp=a;
	
	while(b!=0)
	{ 	
		if (b&1) 
			ans=ans*tmp%c;    //不可以写 ans=ans*ans%c 结果会变
		
		tmp=tmp*tmp%c;
		b=b>>1;
	}
	
	
	return ans;	 
}
bool test(__int64 n,__int64 a,__int64 d)
{
	if (n==2)return true;
	if (n==a)return true;
	if  (  (n&1)==0) return false;
	while(!(d&1))  d=d>>1;
	__int64 t=powe_m(a,d,n);
	while((d!=n-1) && (t!=1)&&(t!=n-1))
	{
		t= (__int64 ) t*t%n;
		d=d<<1;
	}
	return (t==n-1 || (d&1)==1);
}
bool isprime (__int64 n)
{
	if (n<2)return false;
	__int64 a[]={2,3,61,7,13,17,19,23,29,31,37};
	for (int i=0;i<11 ;i++)
		if (!test(n,a[i],n-1))
			return false;
		return true;
}


int main()
{
	int t;
	
	int n,i;
	scanf("%d",&t);
	
	while(t--)
	{
		scanf("%d",&n);
 
		if (isprime(n))
			
		{
			printf("yes\n");
		}
		else
		{
			printf("No\n");
		} 
	}
		
		return 0;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值