Exercices corrigés sur les fonctions récursives -TD1-
Expliquez les fonctionnalités des fonctions suivantes.
Exercice 1
fonction fct1(x,y)
SI x==0 ALORS
retourne y
SINON
retourne fct1(x-1,x+y)
FINSI
def fct1(x,y):
if x==0:
return y
else:
return fct1(x-1,x+y)
Corrigé :
La fonction fct1() calcule et retourne ((1 + 2 ... + x-1 + x) +y) qui est (x(x+1)/2) + y. Par exemple, si x est 5 et y est 2, alors fct1 devrait retourner 15 + 2 = 17.
Exercice 2
fonction fct2(n)
SI n=1 ALORS
retourne 0
SINON
return 1+fct2(n/2)
FINSI
def fct2(n):
if n==0:
return 0
else:
return 1+fct2(n//2)
Corrigé :
La fonction calcule et renvoie le plus grand entier inférieur ou égal à log2(n). Par exemple, si n est entre 8 et 15, fct2() renvoie 3. Si n est entre 16 et 31 alors fct2() renvoie 4.
Exercice 3
fonction fct3(n)
SI n=0 ALORS
retourne
FINSI
fct3(n/2)
Ecrire(n%2)
def fct3(n):
if n==0:
return
fct3(n//2)
print(n % 2, end=" ")
Corrigé :
La fonction fct3() affiche l'équivalent binaire d'un nombre n.
Par exemple, si n est 21, alors fct3() affiche 10101.
Par exemple, si n est 21, alors fct3() affiche 10101.
Partager ce cours avec tes amis :
Rédigé par
ESSADDOUKI
Mostafa
The education of the 21st century opens up opportunities to not merely teach, but to coach, mentor, nurture and inspire.
