Search code examples
algorithmpython-3.xcomplexity-theorytime-complexity

Can I reduce the computational complexity of this?


Well, I have this bit of code that is slowing down the program hugely because it is linear complexity but called a lot of times making the program quadratic complexity. If possible I would like to reduce its computational complexity but otherwise I'll just optimize it where I can. So far I have reduced down to:

def table(n):
    a = 1
    while 2*a <= n:
      if (-a*a)%n == 1: return a

      a += 1

Anyone see anything I've missed? Thanks!

EDIT: I forgot to mention: n is always a prime number.

EDIT 2: Here is my new improved program (thank's for all the contributions!):

def table(n):
    if n == 2: return 1
    if n%4 != 1: return

    a1 = n-1
    for a in range(1, n//2+1):
        if (a*a)%n == a1: return a

EDIT 3: And testing it out in its real context it is much faster! Well this question appears solved but there are many useful answers. I should also say that as well as those above optimizations, I have memoized the function using Python dictionaries...


Solution

  • Based off OP's second edit:

    def table(n):
        if n == 2: return 1
        if n%4 != 1: return
    
        mod = 0
        a1 = n - 1
        for a in xrange(1, a1, 2):
            mod += a
    
            while mod >= n: mod -= n
            if mod == a1: return a//2 + 1