Mathématiques

Question

bonjour, pouvez-vous m'aider pour cette exercice s'il vous plais.
1.On se donne un entier naturel N. Écrire un algorithme qui donne la plus grande puissance k de 2 tel que N ≥ 2k. Tester votre algorithme sur N=213 2.Utiliser votre algorithme pour écrire N=213 comme une somme de puissance de 2.

1 Réponse

  • Réponse :

    Bonsoir,

    Explications étape par étape

    import sys

    def Puis(p):

       N=p

       if N==0 :

           return "-infini"

       rep=1

       k=-1

       Q=0.5

       while N>0:

           k+=1

           N=int(N/2)

           Q=Q*2

       return [k,int(Q)]

    def Som2(p):

       N=p

       Somlist=[]

       aListe=[]

       while N>0:

           aList=Puis(N)

           Somlist.append(aList)

           N=N-aList[1]

       return Somlist

    #-----------------------------------------

    def Prog_1():

       N=0

       while N> -1:

           N=int(input("(-2 pour terminer ) Donnez un entier naturel: "))

           liste=Puis(N)

           print(N,">= 2^",liste[0],"=",liste[1])

       return

    #-----------------------------------------

    def Prog_2():

       N=0

       while N> -1:

           N=int(input("(-2 pour terminer ) Donnez un entier naturel à décomposer: "))

           aSomme=Som2(N)

           print(N,"=^",aSomme )

       return

    #-----------------------------------------

    Prog_1()

    #prog_2()

    sys.exit()

Autres questions