我试图写一个方法来生成高斯整数的高斯除数序列-高斯整数要么是普通整数,要么是复数a和{}都是整数,高斯整数的高斯除数g是高斯整数d,因此{}也是高斯整数。在
我有下面的代码。在def is_gaussian_integer(c):
"""
Checks whether a given real or complex number is a Gaussian integer,
i.e. 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, i.e. 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
它似乎“基本上”起作用,但对于某些输入,它缺少一些高斯除数,例如对于2,我希望序列包含除数{}(它只是-2),但它丢失了。我不明白它为什么要这么做,也不明白逻辑上有什么漏洞。在
^{pr2}$