0

Here is my code:

    import random
def one_d(n):
    b = n
    # initialize n
    s = 0
    # while loop, terminating when s becomes odd
    while n % 2 == 0:
        # increment s
        s = s+1
        # divide n by 2
        n = n/2
    tuple1 = tuple([s,n])
    return tuple1
    print "2^",s,"*",n,"=", b
def miller_rabin(n, a):
    list1 = []
    tuple1 = one_d(n-1)
    for r in xrange(tuple1[0]):
        list1.append((a**(2**(r)*tuple1[1])) % n)
        if list1[r] == n-1 or list1[r] == 1:
            return "True"
    else:
        return "False"
def isprime(n):
    for i in xrange(10):
        a = random.randrange(2, n-1)
        if miller_rabin(n, a) == "False":
            return "False"
    return "True

As I understand it, this test should be able to deal with very large numbers, but my script gets stuck on numbers like 50034901. I'm assuming I've made an error/ grave inefficiency somewhere - since my script still works for smaller numbers.

mrnovice
  • 253
  • 2
  • 5
  • 11

1 Answers1

0

Ok after further investigating I realised it's because I'm using the "%" code to perform my modulus calculation which is much more inefficient than using python's 'pow' function. The former calculates the full exponent before calculating the modulus, and thus has to deal with very large numbers. The latter goes in steps, re-adjusting by modulus n each time and thus is more efficient

mrnovice
  • 253
  • 2
  • 5
  • 11