I am trying to write a method for generating a sequence of Gaussian divisors of a Gaussian integer - a Gaussian integer is either a normal integer or a complex number g = a + bi , where a and b are integers, and a Gaussian divisor of a Gaussian integer g is a Gaussian integer d such that that g / d also a Gaussian integer.
I have the following code.
def is_gaussian_integer(c): """ Checks whether a given real or complex number is a Gaussian integer, ie a complex number g = a + bi such that a and b are integers. """ if type(c) == int: return True return c.real.is_integer() and c.imag.is_integer() def gaussian_divisors(g): """ Generates a sequence of Gaussian divisors of a rational or Gaussian integer g, ie a Gaussian integer d such that g / d is also a Gaussian integer. """ if not is_gaussian_integer(g): return if g == 1: yield complex(g, 0) return g = complex(g) if type(g) == int or type(g) == float else g a = b = 1 ubound = int(math.sqrt(abs(g))) for a in range(-ubound, ubound + 1): for b in range(-ubound, ubound + 1): if a or b: d = complex(a, b) if is_gaussian_integer(g / d): yield d yield g
It seems that βmostlyβ works, but for some inputs it skips some Gaussian dividers, for example. for 2 I expect the sequence to include the divisor -2 + 0j (which is just -2 ), but it is missing. I canβt understand why he does it or where there is a gap in the logic.
In [92]: list(gaussian_divisors(2)) Out[92]: [(-1-1j), (-1+0j), (-1+1j), -1j, 1j, (1-1j), (1+0j), (1+1j), (2+0j)]
source share