Mathématiques en première générale – Algorithmes

Calcul de factorielle

def fact(n) :
    accu = 1
    for i in range(2, n + 1) :
        accu *= i
    return accu

print(fact(1))
print(fact(2))
print(fact(5))
print(fact(200))
1
2
120
788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000

Version récursive

def fact(n) :
    if n <= 1 :
        return 1
    else :
        return n * fact(n - 1)

print(fact(1))
print(fact(2))
print(fact(5))
print(fact(200))
1
2
120
788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000

Version récursive terminale

def fact(n) :
    def aux(k, accu) :
        if k <= 1 :
            return accu
        else :
            return aux(k - 1, k * accu)
    return aux(n, 1)

print(fact(1))
print(fact(2))
print(fact(5))
print(fact(200))
1
2
120
788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000

Version fonctionnelle

from functools import reduce
def fact(n) :
    return reduce(lambda a, b : a * b, range(1, n + 1))

print(fact(1))
print(fact(2))
print(fact(5))
print(fact(200))
1
2
120
788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000
Lionel Avon