Python 3 - 高斯整数的高斯因数
Python 3 - Gaussian divisors of a Gaussian integer
我正在尝试编写一种方法来生成高斯整数的高斯除数序列 - 高斯整数可以是普通整数也可以是复数 g = a + bi
,其中 a
和 b
都是整数,高斯整数 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
它似乎 "mostly" 有效,但对于某些输入,它遗漏了一些高斯除数,例如对于 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)]
而不是屈服
yield g
你还可以
yield -g
因为你的循环开始和停止在 int(math.sqrt(abs(g)))
= int(sqrt(2))
也就是 1
所以它只会测试 -1
, 0
和 1
.
或者,如果您想在循环中包含 -2
和 2
,您需要增加 ubound
或 math.ceil
和 sqrt
结果。
我正在尝试编写一种方法来生成高斯整数的高斯除数序列 - 高斯整数可以是普通整数也可以是复数 g = a + bi
,其中 a
和 b
都是整数,高斯整数 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
它似乎 "mostly" 有效,但对于某些输入,它遗漏了一些高斯除数,例如对于 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)]
而不是屈服
yield g
你还可以
yield -g
因为你的循环开始和停止在 int(math.sqrt(abs(g)))
= int(sqrt(2))
也就是 1
所以它只会测试 -1
, 0
和 1
.
或者,如果您想在循环中包含 -2
和 2
,您需要增加 ubound
或 math.ceil
和 sqrt
结果。