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

  • Home
  • SEARCH
  • 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 6061157
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T08:54:24+00:00 2026-05-23T08:54:24+00:00

I implemented the Miller-Rabin prime test algorithm found on wikipedia with Python 3. It

  • 0

I implemented the Miller-Rabin prime test algorithm found on wikipedia with Python 3.

It seems to be working correctly with most numbers but occasionaly fail on certain numbers.

For example, the prime number 99999999999999997 is judged to be NOT prime.

I implemented the algorithm line by line and I have no clue where the problem is.
Can any one help me ?

Here is my code.

the test input is:

1

99999999999999997

(No empty line between two lines.)

And the expected output should be YES, but it gives NO on my machine.

import random

def isPrime(n, k = 5):
'''
Primality test using Miller-Rabin method.
n The number to test primality.
k The number of M-R test to perform.
'''
if n == 1:
    return False
if n == 2 or n == 3:
    return True
if n % 2 == 0:
    return False

# Calculate d
nn = n - 1
s = 1
while nn % (2 ** s) == 0:
    s += 1
s -= 1
d = int(nn / (2 ** s))

for i in range(k):
    a = random.randint(2, n - 1)
    x = pow(a,d,n)
    if x == 1 or x == n - 1:
        continue
    flag = True
    for r in range(1, s):
        x = pow(x,2,n)
        if x == 1:
            return False
        if x == n - 1:
            flag = False
            break
    if not flag:
        continue
    return False
return True

count = int(input())
for i in range(count):
    if isPrime(int(input())):
        print('YES')
    else:
        print('NO')
  • 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-05-23T08:54:24+00:00Added an answer on May 23, 2026 at 8:54 am

    This is an implementation of Miller-Rabin I wrote a while ago. It has never given me an unexpected result — though that doesn’t mean it won’t! It is substantially identical to the one you pasted, and it declares 99999999999999997 to be prime. Yours did too, when I tested it — so that’s a second to Mikola’s opinion. But see below for one possible problem that I can’t easily test… scratch that, I tested it, and it was the problem.

    When it comes to primality testing, I’m no expert, but I spent a lot of time thinking about and coming to understand Miller-Rabin, and I’m pretty sure your implementation is spot-on.

    def is_prime_candidate(self, p, iterations=7):  
        if p == 1 or p % 2 == 0: return False       
        elif p < 1: raise ValueError("is_prime_candidate: n must be a positive integer")
        elif p < self.maxsmallprime: return p in self.smallprimes
    
        odd = p - 1
        count = 0
        while odd % 2 == 0:
            odd //= 2
            count += 1
    
        for i in range(iterations):
            r = random.randrange(2, p - 2) 
            test = pow(r, odd, p)
            if test == 1 or test == p - 1: continue
            for j in range(count - 1):
                test = pow(test, 2, p)
                if test == 1: return False
                if test == p - 1: break
            else: return False
            print i
        return True
    

    The one thing I noticed about your code that seemed off was this:

    d = int(nn / (2 ** s))
    

    Why int, I thought to myself. Then I realized you must be using Python 3. So that means you’re doing floating point arithmetic here and then converting to int. That seemed iffy. So I tested it on ideone. And lo! the result was False. So I changed the code to use explicit floor division (d = nn // (2 ** s)). And lo! it was True.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

As an exercise for myself, I'm implementing the Miller-Rabin test. (Working through SICP). I
All, I have implemented a code that generates 2 random prime numbers and the
I implemented the Edmonds–Karp algorithm using the Pseudocode that I found in the Edmonds–Karp
I implemented OpenID support for an ASP.Net 2.0 web application and everything seems to
Having implemented CLogClass to make decent logging I also defined macro, but it works
i implemented a small code to show pictures, but why is the picture on
I implemented something in Windows Forms similar to DragMove but with boundaries set to
I implemented a custom list view, but now there's no visual feedback that an
I implemented RestSharp succesfully in my WP7 application, but one issue remains: When I
I implemented an rpc call. It works on local machine but does not work

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.