Python 3 - 高斯整数的高斯除数

6
我正在尝试编写一个方法来生成高斯整数的高斯除数序列-高斯整数可以是普通整数或复数g = a + bi,其中ab都是整数,高斯整数g的高斯除数是一个高斯整数d,使得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+0j(就是-2),但它确实缺失了。我无法弄清楚为什么会这样做或逻辑中存在哪些差距。

In [92]: list(gaussian_divisors(2))
Out[92]: [(-1-1j), (-1+0j), (-1+1j), -1j, 1j, (1-1j), (1+0j), (1+1j), (2+0j)]

在Python 3中,整数除法运算符是//,而不是/。对于复数操作数,我不知道它的作用。 - President James K. Polk
我认为//运算符不适用于复数,例如1 / 1j会按预期给出-1j,但是1 // -1j会抛出错误:TypeError: can't take floor of complex number.。这可能是因为与整数不同,复数没有自然排序。 - srm
好的,您可能需要定义自己的整除运算符,因为对于足够大的操作数,“/”将无法正确工作。此外,对于“g = 2”,“ubound = 1”,因此您的循环从-1到1。您从未测试过-2。 - President James K. Polk
你的条件 if g == 1: yield complex(g, 0) return 是不正确的。数字 1 的因数是 1,-1,i,-i - Stef
我建议阅读这个问题的启发性答案:什么是分解高斯整数的好方法? - Stef
1个回答

1

不是仅仅产生

yield g

你还可以额外添加。
yield -g

因为你的循环从 int(math.sqrt(abs(g))) = int(sqrt(2)) 开始和停止,这只是 1 所以它将测试 -101
或者,如果你想在循环中包括 -22,你需要增加 ubound 或对 sqrt 的结果进行 math.ceil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接