简体   繁体   中英

Find the Greatest Common Divisor (GCD) in Gaussian Integers with SymPy

I try to find the GCD of two gaussian integers using Sympy but couldn't get the correct result. For example, the function

gcd(2+I,5, gaussian = True)

should return 2+I (I is the imaginary unit) because (2+I)*(2-I)=5 in gaussian integers. However it returns 1 .

Looks like gcd is insufficiently aware of Gaussian integers (ie, a bug). You can use your own function, though, based on the Euclidean algorithm.

from sympy import sympify, I, expand_mul
def my_gcd(a, b):
    a, b = map(sympify, (a, b))
    if abs(a) < abs(b):
        a, b = b, a
    cr, ci = (a/b).as_real_imag()
    if cr.is_integer and ci.is_integer:
        return -b if b.could_extract_minus_sign() else b
    c = int(round(cr)) + I*int(round(ci))
    return my_gcd(a - expand_mul(b*c), b)

Testing:

my_gcd(30, 18)   #  6
my_gcd(5, 2+I)   #  2+I
my_gcd(30, 18+4*I)   # 4 + 2*I

Checking the last of these: 30 = (4+2*I)*(6-3*I) and 18+4*I = (4+2*I)*(4-I) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM