pgcdppcm.py

Created by nicolas-patrois

Created on July 22, 2020

650 Bytes

Calcule le PGCD et le PPCM de nombres. Le PGCD fonctionne seul, le PPCM utilise une méthode d’exclusion-inclusion et donc des combinaisons (sans itertools).


def combinations(liste):
  n=len(liste)
  for i in range(2**n):
    b=[int(j) for j in bin(i)[2:]]
    b=[0]*(n-len(b))+b # rjust n'est pas disponible
    yield [liste[j] for j in range(n) if b[j]]

def pgcd(*args):
  if len(args)==0:
    return 1
  a=args[0]
  d=a
  for b in args[1:]:
    while b:
      d=b
      a,c=divmod(a,b)
      a,b=b,c
  return d

def ppcm(*args):
  n=len(args)
  p=1
  q=1
  for l in combinations(args):
    if len(l)%2:
      p*=pgcd(*l)
    else:
      q*=pgcd(*l)
  return p//q

if __name__=="__main__":
  print("PGCD(150,180,240)=%d"%pgcd(150,180,240))
  print("PPCM(150,180,240)=%d"%ppcm(150,180,240))

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.