Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

NumPy GCD 最大公约数


求最大公约数 (GCD)

最大公约数 (GCD),也称为最大公因数 (HCF),是指两个数的公因数中最大的一个。

示例

求以下两个数的最大公因数

import numpy as np

num1 = 6
num2 = 9

x = np.gcd(num1, num2)

print(x)
自己尝试一下 »

返回值: 3,因为这是这两个数都可以被整除的最大数 (6/3=2 和 9/3=3)。


在数组中求最大公约数

要查找数组中所有值的最高公因数,可以使用 reduce() 方法。

reduce() 方法将对每个元素使用 ufunc,在本例中为 gcd() 函数,并将数组的维度减少一个。

示例

求以下数组中所有数字的最大公约数

import numpy as np

arr = np.array([20, 8, 32, 36, 16])

x = np.gcd.reduce(arr)

print(x)
自己尝试一下 »

返回值: 4,因为这是所有值都可以被整除的最大数。



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.