Re: Relatively prime integers in NumPy

Liste des GroupesRevenir à cl python 
Sujet : Re: Relatively prime integers in NumPy
De : oscar.j.benjamin (at) *nospam* gmail.com (Oscar Benjamin)
Groupes : comp.lang.python
Date : 11. Jul 2024, 23:22:30
Autres entêtes
Message-ID : <mailman.30.1720732964.2981.python-list@python.org>
References : 1 2
(posting on-list this time)

On Thu, 11 Jul 2024 at 15:18, Popov, Dmitry Yu via Python-list
<python-list@python.org> wrote:
>
Dear Sirs.
>
Does NumPy provide a simple mechanism to identify relatively prime integers, i.e. integers which don't have a common factor other than +1 or -1? For example, in case of this array:
[[1,5,8],
  [2,4,8],
  [3,3,9]]
I can imagine a function which would return array of common factors along axis 0: [1,2,3]. Those triples of numbers along axis 1 with the factor of1 or -1 would be relatively prime integers.

It sounds like you want the gcd (greatest common divisor) of each row.
The math module can do this:

In [1]: a = [[1,5,8],
   ...:   [2,4,8],
   ...:   [3,3,9]]

In [2]: import math

In [3]: [math.gcd(*row) for row in a]
Out[3]: [1, 2, 3]

NumPy can also do it apparently:

In [10]: np.gcd.reduce(np.transpose(a))
Out[10]: array([1, 2, 3])

https://en.wikipedia.org/wiki/Greatest_common_divisor

--
Oscar

Date Sujet#  Auteur
11 Jul 24 o Re: Relatively prime integers in NumPy1Oscar Benjamin

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal