Description
Give you a lot of positive integers, just to find out how many prime numbers there are ..
In each case, there is an integer n representing the number of Integers to find. each integer won't exceed 32-bit signed integer, and each of them won't be less than 2.
32-Bit Signed intege, the most common is to time out, the memory method to exceed the memory, if it is small, it will cross the border.
Miller_rabinAlgorithm
I. ferma xiaodingli
If n is prime and gcd (A, n) equals one, then a ^ (n-1) = 1 (mod N)
The ferma's theorem is only a necessary condition. The number that conforms to the ferma's theorem rather than the prime number is called Carmichael.
The first three Carmichael numbers are 1729.
There are very few Carmichael numbers.
In 1 ~ Of the integers in the range of 100000000, there are only 255 Carmichael numbers.
Therefore, there is a quadratic probe theorem to ensure that this number is a prime number:
Ii. Quadratic probe Theorem
Quadratic probe theorem if p is a prime number, 0 <x <p, then the solution of equation x ^ 2 limit 1 (mod P) is x = 1 P-1
According to the above two theorems, such as the general steps to the Miller-Rabin algorithm:
0. Calculate m and J so that n-1 = m * 2 ^ J, where M is a positive odd number, and J is a non-negative integer.
1. Random B, 2 <= B
2. Calculate v = B ^ m mod n
3. If v = 1, pass the test and return
4. Make I = 1
5. If v = n-1, pass the test and return
6. If I = J, non-prime number, end
7. V = V ^ 2 mod N, I = I + 1
8. loop to 5
Note:
Miller-Rabin is a random algorithm.
The accuracy of the result is 75%. Therefore, you should call this function multiple times to increase the probability of correctness to 1-(1/4) ^ s.
Jie yunpeng, do you understand?
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <math.h>#include <iostream>#include <algorithm>#define ll long longusing namespace std;const int INF = 0x3f3f3f3f;int i, j, k;ll m, b;int numCase;ll n;bool flag;int S = 5;ll quickpow(ll m,ll n,ll k){ int b = 1; while (n > 0){ if (n & 1) b = (b*m)%k; n = n >> 1 ; m = (m*m)%k; } return b;}bool Miller_Rabin(){ int temp_n = n -1; j = 0; while(temp_n % 2 == 0){ ++j; temp_n /= 2; } m = (n -1) / (1 << j); int v = quickpow(b, m, n); if(1 == v){ flag = true; return flag; } int i = 0; while(++i <= 5){ if(v == n - 1){ flag = true; } else if(i == j){ flag = false; return flag; } }}bool witness(ll a,ll n){ ll 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(ll n){ int s[]={2,7,61}; if(n==2) return true; if(n==1 || ((n&1)==0)) return false; for(int i=0;i<3;i++) if(witness(s[i], n)) return false; return true;}int main(){ while(EOF != scanf("%d",&numCase)){ flag = false; int count = 0; while(numCase--){ cin >> n; if(miller_rabin(n)) ++count; } cout << count << endl; } return 0;}