How to resolve the algorithm Miller–Rabin primality test step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Miller–Rabin primality test step by step in the Swift programming language

Table of Contents

Problem Statement

The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not. The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm. The pseudocode, from Wikipedia is:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Miller–Rabin primality test step by step in the Swift programming language

Source code in the swift programming language

import BigInt

private let numTrails = 5

func isPrime(_ n: BigInt) -> Bool {
  guard n >= 2 else { fatalError() }
  guard n != 2 else { return true }
  guard n % 2 != 0 else { return false }

  var s = 0
  var d = n - 1

  while true {
    let (quo, rem) = (d / 2, d % 2)

    guard rem != 1 else { break }

    s += 1
    d = quo
  }

  func tryComposite(_ a: BigInt) -> Bool {
    guard a.power(d, modulus: n) != 1 else { return false }

    for i in 0..<s where a.power((2 as BigInt).power(i) * d, modulus: n) == n - 1 {
      return false
    }

    return true
  }

  for _ in 0..<numTrails where tryComposite(BigInt(BigUInt.randomInteger(lessThan: BigUInt(n)))) {
    return false
  }

  return true
}


  

You may also check:How to resolve the algorithm Doomsday rule step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Pascal's triangle step by step in the Groovy programming language
You may also check:How to resolve the algorithm Function definition step by step in the Slate programming language
You may also check:How to resolve the algorithm Array length step by step in the Raku programming language
You may also check:How to resolve the algorithm Brownian tree step by step in the PicoLisp programming language