Aritmetica: somma

Iterativa

Osserva le diverse versioni

  1. M+N = M+1 ... +1 (N volte)
  2. M+N = ((...((M+1)+1)...)+1)
  3. Somma(M, N) = Successivo(Successivo(...Successivo(M)...))
  4. Somma(M, N) = SuccessivoN(M)
Function SomIter(M, N: LongInt): LongInt;
Var
   I: LongInt;
Begin
   For I:=1 To N Do
      Inc(M);         { M:=M+1; } { M:=Succ(M); }
   SomIter:=M;
End;
apri M dita della mano destra
apri N dita della mano sinistra
mentre la mano sinistra non è chiusa esegui
inizio
   apri un dito a destra
   chiudi un dito a sinistra
fine
la risposta è nella mano destra
Function SomIter(M, N: LongInt): LongInt;
Begin
   While(N > 0) Do
      Begin
         Inc(M);
         Dec(N);
      End;
   SomIter:=M
End;
Function SomIter(M, N: LongInt): LongInt;
Var
   I: LongInt;
Begin
   For I:=N DownTo 1 Do
      Inc(M);
   SomIter:=M;
End;

Ricorsiva

  • Somma(M, N) = M, per N = 0
  • Somma(M, N) = 1+Somma(M, N-1), altrimenti

Esempio

M=5, N=3

Somma(5, 3) = 1+Somma(5, 2) = 1+7 = 8
Somma(5, 2) = 1+Somma(5, 1) = 1+6 = 7
Somma(5, 1) = 1+Somma(5, 0) = 1+5 = 6
Somma(5, 0) = 5
Function SomRic(M, N: LongInt): LongInt;
Begin
   If(N = 0) Then
      SomRic:=M
   Else
      SomRic:=SomRic(M, N-1)+1;
End;

Ricorsiva

  • Somma(M, N) = M, per N = 0
  • Somma(M, N) = Successivo(Somma(M, Precedente(N))), altrimenti

Esempio

M=5, N=3

Somma(5, 3) = Successivo(Somma(5, Precedente(3)) = Successivo(Somma(5, 2)) = Successivo(7) = 8
Somma(5, 2) = Successivo(Somma(5, Precedente(2)) = Successivo(Somma(5, 1)) = Successivo(6) = 7
Somma(5, 1) = Successivo(Somma(5, Precedente(1)) = Successivo(Somma(5, 0)) = Successivo(5) = 6
Somma(5, 0) = 5
Function SomRic(M, N: LongInt): LongInt;
Begin
   If(N = 0) Then
      SomRic:=M
   Else
      SomRic:=SomRic(M, N-1)+1;
End;
Function SomRic(M, N: LongInt): LongInt;
Begin
   If(N = 0) Then
      SomRic:=M
   Else
      SomRic:=Succ(SomRic(M, Pred(N)));
End;

Oppure

  • Somma(M, N) = M, per N = 0
  • Somma(M, N) = Somma(M+1, N-1), altrimenti
Function SomRic(M, N: LongInt): LongInt;
Begin
   If(N = 0) Then
      SomRic:=M
   Else
      SomRic:=SomRic(M+1, N-1);
End;

Oppure

  • Somma(M, N) = M, per N = 0
  • Somma(M, N) = Somma(Successivo(M), Precedente(N)), altrimenti

Esempio

M=5, N=3

Somma(5, 3) = Somma(Successivo(5), Precedente(3)) = Somma(6, 2) = 8
Somma(6, 2) = Somma(Successivo(6), Precedente(2)) = Somma(7, 1) = 8
Somma(7, 1) = Somma(Successivo(7), Precedente(1)) = Somma(8, 0) = 8
Somma(8, 0) = 8
Function SomRic(M, N: LongInt): LongInt;
Begin
   If(N = 0) Then
      SomRic:=M
   Else
      SomRic:=SomRic(Succ(M), Pred(N));
End;