生活随笔
收集整理的這篇文章主要介紹了
素数相关模板
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
線性篩素數:
#include <bits/stdc++.h>
using namespace std
;
const int N
= 1e7+5;
bool mp
[N
];
int prime
[N
];
void getPrime(int n
)
{int cnt
= 0;for(int i
= 2; i
<= n
; i
++){if(!prime
[i
]) prime
[++cnt
] = i
;for(int j
= 1; j
<=cnt
&&prime
[j
]<=n
/i
; j
++){prime
[i
*prime
[j
]] = 1;if(i
%prime
[j
] == 0) break;}}for(int i
= 1; i
<= cnt
; i
++){mp
[prime
[i
]] = true
;}
}
int main()
{int n
,t
;scanf("%d%d",&n
,&t
);getPrime(n
);int x
;while(t
--){scanf("%d",&x
);if(mp
[x
]) puts("Yes");else puts("No");}return 0;
}
米勒卡賓判素數:
#include <bits/stdc++.h>
using namespace std
;
typedef long long LL
;
LL
quickPow(LL a
,LL b
,LL mod
)
{LL res
= 1;a
%= mod
;while(b
){if(b
&1) res
= res
*a
%mod
;b
>>= 1;a
= a
*a
%mod
;}return res
%mod
;
}
LL num
[] = {2,3,5,7,11,13,17,19};
bool
Miller_Rabin(LL x
)
{if(x
== 2) return true
;if((x
&1)==0||x
==1) return false
;for(LL i
= 0; i
< 8; i
++)if(x
== num
[i
]) return true
;LL tmp
= x
-1;LL t
= 0,nxt
;while((tmp
&1)==0){tmp
>>=1;t
++;}for(LL i
= 0; i
< 8; i
++){LL a
= num
[i
];LL now
= quickPow(a
,tmp
,x
);nxt
= now
;for(LL j
= 1; j
<= t
; j
++){nxt
= now
* now
% x
;if(nxt
==1 && now
!= x
-1 && now
!= 1)return false
;now
= nxt
;}if(now
!= 1) return false
;}return true
;
}
int main()
{LL n
,m
;cin
>>n
>>m
;LL x
;while(m
--){cin
>>x
;cout
<<(Miller_Rabin(x
)?"Yes":"No")<<endl
;}return 0;
}
總結
以上是生活随笔為你收集整理的素数相关模板的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。