Primality Testing、Miller Rabin Algorithm

Primality Testing

Determine whether a given large number is prime, traditionally sieve using trial division.

 

Two properties of prime numbers:

  • property 1

if p is prime and a is a positive integer with a<p,

a^2 mod p =1 if and only if   a mod p =1 or a mod p =-1 mod p =p-1

  • property  2

 

 

Miller Rabin Algorithm

Test(n) :

  1. find integers k , q with k>0 , q odd, so that (n-1)=2^k *q
  2. select a random integer a, 1<a<n-1
  3. if a^q mod n =1 then return ('inconclusive')
  4. for j=0 to k-1 do  
  5. if (a^((2^j)*q)) mod n =n-1)         then  return("inconclusive")
  6. return ("composite")

   

example 1:

Test   n=29 

29-1 = 2^2 * 7, thus k=2, q=7

a^q mod n= 2^7 mod 29 = 12!=1!=29-1

then 12^2=144 mod 29=28= 29-1

test returns "inconclusive"(propaly prime)

 

example 2:

Test n=2047   a=2

2047-1 = 2046= 2^1 * 1023,  thus k=1 , q=1023

a^q mod n= 2^1023 mod 2047= 1

 

2^1=2

2^2= 4

2^4=16 

2^8=256

2^16=65536 = 32 (mod 2047)

2^32=1024 

2^64=512 (mod 2047)

2^128=128 (mod 2047)

2^256= 8 (mod 2047)

2^512=64 

2^1023=2^(512+256+128+64+32+16+8+4+2+1)

=64*8*128*512*1024*32*256*16*4*2 (mod 2047)

=8*256 mod 2047

=1 mod 2047

总结:  2^1023 mod 2047=  这类计算化简,不管mod 前面数有多大都要化简到2047的最小倍数然后得出其余数

以下是 Miller-Rabin 素性测试算法的 Matlab 代码。 ```matlab function is_prime = miller_rabin(n, k) % MILLER_RABIN performs Miller-Rabin primality test on n % n: the integer to be tested % k: number of iterations % is_prime: boolean value indicating whether n is prime or not if mod(n, 2) == 0 is_prime = false; return end d = n-1; r = 0; while mod(d, 2) == 0 d = d / 2; r = r + 1; end for i = 1:k a = randi([2, n-2]); x = mod_exp(a, d, n); if x == 1 || x == n-1 continue end for j = 1:r-1 x = mod(x^2, n); if x == n-1 break end end if x ~= n-1 is_prime = false; return end end is_prime = true; end function res = mod_exp(a, b, n) % MOD_EXP computes a^b mod n using the square-and-multiply algorithm % a: base % b: exponent % n: modulus % res: result res = 1; while b > 0 if mod(b, 2) == 1 res = mod(res * a, n); end a = mod(a^2, n); b = b / 2; end end ``` 其中,`miller_rabin` 函数接受两个参数:待测试的正整数 `n` 和测试次数 `k`,并返回一个布尔值,表示 `n` 是否为素数。该函数首先判断 `n` 是否为偶数,若是则直接返回 `false`,否则寻找整数 `d` 和 `r`,使得 `n-1 = 2^r * d`,其中 `d` 为奇数。然后对于 `k` 次随机选取的整数 `a`,利用 `mod_exp` 函数计算 `a^d mod n`,若结果为 1 或 `n-1` 则进行下一次测试,否则继续计算其平方取模的结果,直到结果为 `n-1` 或达到 `r-1` 次。如果仍然不满足,则 `n` 被判定为合数;若所有测试均通过,则 `n` 被判定为素数。 `mod_exp` 函数用于计算幂运算的结果,采用了平方-乘法算法,可以有效减少计算量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值