Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9215617
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T02:14:37+00:00 2026-06-18T02:14:37+00:00

Been trying to implement Rabin-Miller Strong Pseudoprime Test today. Have used Wolfram Mathworld as

  • 0

Been trying to implement Rabin-Miller Strong Pseudoprime Test today.

Have used Wolfram Mathworld as reference, lines 3-5 sums up my code pretty much.

However, when I run the program, it says (sometimes) that primes (even low such as 5, 7, 11) are not primes. I’ve looked over the code for a very long while and cannot figure out what is wrong.

For help I’ve looked at this site aswell as many other sites but most use another definition (probably the same, but since I’m new to this kind of math, I can’t see the same obvious connection).

My Code:

import random

def RabinMiller(n, k):

    # obviously not prime
    if n < 2 or n % 2 == 0:
        return False

    # special case        
    if n == 2:
        return True

    s = 0
    r = n - 1

    # factor n - 1 as 2^(r)*s
    while r % 2 == 0:
        s = s + 1
        r = r // 2  # floor

    # k = accuracy
    for i in range(k):
        a = random.randrange(1, n)

        # a^(s) mod n = 1?
        if pow(a, s, n) == 1:
            return True

        # a^(2^(j) * s) mod n = -1 mod n?
        for j in range(r):
            if pow(a, 2**j*s, n) == -1 % n:
                return True

    return False

print(RabinMiller(7, 5))

How does this differ from the definition given at Mathworld?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T02:14:38+00:00Added an answer on June 18, 2026 at 2:14 am

    1. Comments on your code

    A number of the points I’ll make below were noted in other answers, but it seems useful to have them all together.

    1. In the section

      s = 0
      r = n - 1
      
      # factor n - 1 as 2^(r)*s
      while r % 2 == 0:
          s = s + 1
          r = r // 2  # floor
      

      you’ve got the roles of r and s swapped: you’ve actually factored n − 1 as 2sr. If you want to stick to the MathWorld notation, then you’ll have to swap r and s in this section of the code:

      # factor n - 1 as 2^(r)*s, where s is odd.
      r, s = 0, n - 1
      while s % 2 == 0:
          r += 1
          s //= 2
      
    2. In the line

      for i in range(k):
      

      the variable i is unused: it’s conventional to name such variables _.

    3. You pick a random base between 1 and n − 1 inclusive:

      a = random.randrange(1, n)
      

      This is what it says in the MathWorld article, but that article is written from the mathematician’s point of view. In fact it is useless to pick the base 1, since 1s = 1 (mod n) and you’ll waste a trial. Similarly, it’s useless to pick the base n − 1, since s is odd and so (n − 1)s = −1 (mod n). Mathematicians don’t have to worry about wasted trials, but programmers do, so write instead:

      a = random.randrange(2, n - 1)
      

      (n needs to be at least 4 for this optimization to work, but we can easily arrange that by returning True at the top of the function when n = 3, just as you do for n = 2.)

    4. As noted in other replies, you’ve misunderstood the MathWorld article. When it says that “n passes the test” it means that “n passes the test for the base a“. The distinguishing fact about primes is that they pass the test for all bases. So when you find that as = 1 (mod n), what you should do is to go round the loop and pick the next base to test against.

      # a^(s) = 1 (mod n)?
      x = pow(a, s, n)
      if x == 1:
          continue
      
    5. There’s an opportunity for optimization here. The value x that we’ve just computed is a20 s (mod n). So we could test it immediately and save ourselves one loop iteration:

      # a^(s) = ±1 (mod n)?
      x = pow(a, s, n)
      if x == 1 or x == n - 1:
          continue
      
    6. In the section where you calculate a2j s (mod n) each of these numbers is the square of the previous number (modulo n). It’s wasteful to calculate each from scratch when you could just square the previous value. So you should write this loop as:

      # a^(2^(j) * s) = -1 (mod n)?
      for _ in range(r - 1):
          x = pow(x, 2, n)
          if x == n - 1:
              break
      else:
          return False
      
    7. It’s a good idea to test for divisibility by small primes before trying Miller–Rabin. For example, in Rabin’s 1977 paper he says:

      In implementing the algorithm we incorporate some laborsaving steps. First we test for divisibility by any prime p < N, where, say N = 1000.

    2. Revised code

    Putting all this together:

    from random import randrange
    
    small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] # etc.
    
    def probably_prime(n, k):
        """Return True if n passes k rounds of the Miller-Rabin primality
        test (and is probably prime). Return False if n is proved to be
        composite.
    
        """
        if n < 2: return False
        for p in small_primes:
            if n < p * p: return True
            if n % p == 0: return False
        r, s = 0, n - 1
        while s % 2 == 0:
            r += 1
            s //= 2
        for _ in range(k):
            a = randrange(2, n - 1)
            x = pow(a, s, n)
            if x == 1 or x == n - 1:
                continue
            for _ in range(r - 1):
                x = pow(x, 2, n)
                if x == n - 1:
                    break
            else:
                return False
        return True
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've been trying to implement Rabin-Karp algorithm in Java. I have hard time computing
I have been trying to implement an upgrade plan for my Android app which
I have been trying to implement a GlassPane for my games' in-game HUD, but
Hello guys, I have been trying to implement the DSUM function but failed to
I have been trying to implement twitter bootstrap extension in Yii but cannot do
I have been trying to implement Cascading in my MVC application. Seems like everything
I have been trying to implement a factorial function using the actor model with
I have been trying to implement Win32's MessageBox using GTK. The app uses SDL/OpenGL,
I have been trying to implement a stack on dev c with c ,
I have recently been trying to implement my first Android game using a similar

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.