【算法概論】1.數字的算法

1 數字的算法

1.1 基本算數

1.1.1 加法

  • 加法複雜度O(n)

1.1.2 乘法和除法

  • (複雜度O(n2) )
funtion multiply(x,y)
  Input:Two n-bit integers x and y, where y ≥ 0
  Output:Their product

  if y=0: return 0
  z = multiply(x,⌊ y/2 ⌋)
  if y is even:
    return 2z
  else
    return x+2z
function divide(x,y)
  Input:Two n-bit integers x and y, where y ≥ 1
  Output:Their quotinent and remainder of x divided by y

  if x=0: return (q,r)=(0,0)
  (q,r)=divide(⌊ x/2 ⌋,y)
  q=2q,r=2r
  if x is odd: r=r+1
  if r≥y: r=r-y,q=q+1
  return (q,r)

1.2 模運算

  • xymodN ,複雜度O(log ylog2N)
function modexp(x,y,N)
  Input:Two n-bit integers x and N, an interger exponent y
  Output:x^y mod N

  if y=0: return 1
  z=modexp(x,⌊ y/2 ⌋,N)
  if y is even:
    return z^2 mod N
  else
    return x*z^2 mod N
  • Euclid求最大公因數:gcd(x,y)=gcd(xy,y) ,複雜度O(n3)
function Euclid(a,b)
  Input:Two n-bit integers a and b, with a ≥ b ≥ 0
  Output: gcd(a,b)

  if b=0: return a
  return Euclid(b,a mod b)
  • Euclid擴展算法
function extended_Euclid(a,b)
  Input:Two n-bit integers a and b, with a ≥ b ≥ 0
  Output: Integers x,y,d such that d=gcd(a,b) and ax+by=d

  if b=0: return (1,0,a)
  (x,y,d)=extended_Euclid(b,a mod b)
  return (y,x-⌊ a/b ⌋*y,d)

1.3 素數測試

  • 費馬小定理:如果 p 是一個素數,對任意 1a<p ,有 ap11(modp)
  • 費馬小定理素數測試(出錯率1/2 )
function primality(N)
  Input: Positive integers N
  Output: yes/no

  Pick a positive integer a < N at rondom
  if a^(N-1)=1 (mod N):
    return yes
  else:
    return no
  • 低出錯率(1/2k )費馬小定理素數測試
function primality2(N)
  Input: Positive integers N
  Output: yes/no

  Pick a positive integer a1,a2,...,ak < N at rondom
  if ai^(N-1)=1 (mod N) for all i=1,2,...,k:
    return yes
  else:
    return no
發佈了15 篇原創文章 · 獲贊 26 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章