logo

Co to jest rekurencja ogona

Rekurencja ogona definiuje się jako funkcję rekurencyjną, w której wywołaniem rekurencyjnym jest ostatnia instrukcja wykonywana przez tę funkcję. Zasadniczo po wywołaniu rekurencji nie pozostaje już nic do wykonania.

Na przykład poniższa funkcja C++ print() jest rekurencyjna.



C








// An example of tail recursive function> void> print(>int> n)> {> >if> (n <0)> >return>;> >printf>(>'%d '>, n);> >// The last executed statement is recursive call> >print(n - 1);> }>

>

>

C++




// An example of tail recursive function> static> void> print(>int> n)> {> >if> (n <0)> >return>;> >cout <<>' '> << n;> > >// The last executed statement is recursive call> >print(n - 1);> }> // This code is contributed by Aman Kumar>

>

>

Jawa




// An example of tail recursive function> static> void> print(>int> n)> {> >if> (n <>0>)> >return>;> >System.out.print(>' '> + n);> >// The last executed statement> >// is recursive call> >print(n ->1>);> }> // This code is contributed by divyeh072019>

>

>

Python3




# An example of tail recursive function> def> prints(n):> >if> (n <>0>):> >return> >print>(>str>(n), end>=>' '>)> ># The last executed statement is recursive call> >prints(n>->1>)> ># This code is contributed by Pratham76> ># improved by ashish2021>

>

>

C#




// An example of tail recursive function> static> void> print(>int> n)> {> >if> (n <0)> >return>;> >Console.Write(>' '> + n);> >// The last executed statement> >// is recursive call> >print(n - 1);> }> // This code is contributed by divyeshrabadiya07>

>

>

JavaScript




> // An example of tail recursive function> function> print(n)> {> >if> (n <0)> >return>;> > >document.write(>' '> + n);> > >// The last executed statement> >// is recursive call> >print(n - 1);> }> // This code is contributed by Rajput-Ji> >

>

>

Złożoność czasowa: NA)
Przestrzeń pomocnicza: NA)

Potrzeba rekurencji ogona:

Funkcje rekurencyjne ogona są uważane za lepsze niż funkcje rekurencyjne bez ogona, ponieważ rekurencja ogona może zostać zoptymalizowana przez kompilator.

Kompilatory zwykle wykonują procedury rekurencyjne, używając a stos . Stos ten składa się ze wszystkich istotnych informacji, w tym wartości parametrów, dla każdego wywołania rekurencyjnego. Gdy wywoływana jest procedura, zawarte w niej informacje są takie pchnięty na stos, a kiedy funkcja kończy się, informacja jest wyskoczył ze stosu. Zatem dla funkcji nierekursywnych, the głębokość stosu (maksymalna ilość miejsca na stosie używana w dowolnym momencie podczas kompilacji) jest większa.

Pomysł zastosowany przez kompilatory do optymalizacji funkcji rekursywnych jest prosty, ponieważ wywołanie rekurencyjne jest ostatnią instrukcją, w bieżącej funkcji nie ma już nic do zrobienia, więc zapisywanie ramki stosu bieżącej funkcji nie ma sensu (zobacz więcej Detale).

Czy funkcję nierekurencyjną można zapisać jako rekursywną, aby ją zoptymalizować?

Rozważ następującą funkcję, aby obliczyć silnię n.

Jest to funkcja nierekurencyjna. Chociaż na pierwszy rzut oka wygląda to na rekurencyjny ogon. Jeśli przyjrzymy się bliżej, zobaczymy, że używana jest wartość zwrócona przez fakt (n-1). fakt(n) . Zatem wezwanie do fakt(n-1) nie jest ostatnią rzeczą, którą zrobił fakt(n) .

C++




#include> using> namespace> std;> // A NON-tail-recursive function. The function is not tail> // recursive because the value returned by fact(n-1) is used> // in fact(n) and call to fact(n-1) is not the last thing> // done by fact(n)> unsigned>int> fact(unsigned>int> n)> {> >if> (n <= 0)> >return> 1;> >return> n * fact(n - 1);> }> // Driver program to test above function> int> main()> {> >cout << fact(5);> >return> 0;> }>

>

>

Jawa




class> GFG {> >// A NON-tail-recursive function.> >// The function is not tail> >// recursive because the value> >// returned by fact(n-1) is used> >// in fact(n) and call to fact(n-1)> >// is not the last thing done by> >// fact(n)> >static> int> fact(>int> n)> >{> >if> (n ==>0>)> >return> 1>;> >return> n * fact(n ->1>);> >}> >// Driver program> >public> static> void> main(String[] args)> >{> >System.out.println(fact(>5>));> >}> }> // This code is contributed by Smitha.>

>

>

Python3




# A NON-tail-recursive function.> # The function is not tail> # recursive because the value> # returned by fact(n-1) is used> # in fact(n) and call to fact(n-1)> # is not the last thing done by> # fact(n)> def> fact(n):> >if> (n>=>=> 0>):> >return> 1> >return> n>*> fact(n>->1>)> # Driver program to test> # above function> if> __name__>=>=> '__main__'>:> >print>(fact(>5>))> # This code is contributed by Smitha.>

>

>

C#




using> System;> class> GFG {> >// A NON-tail-recursive function.> >// The function is not tail> >// recursive because the value> >// returned by fact(n-1) is used> >// in fact(n) and call to fact(n-1)> >// is not the last thing done by> >// fact(n)> >static> int> fact(>int> n)> >{> >if> (n == 0)> >return> 1;> >return> n * fact(n - 1);> >}> >// Driver program to test> >// above function> >public> static> void> Main() { Console.Write(fact(5)); }> }> // This code is contributed by Smitha>

>

>

PHP




// A NON-tail-recursive function. // The function is not tail // recursive because the value // returned by fact(n-1) is used in // fact(n) and call to fact(n-1) is // not the last thing done by fact(n) function fact( $n) { if ($n == 0) return 1; return $n * fact($n - 1); } // Driver Code echo fact(5); // This code is contributed by Ajit ?>>

>

>

JavaScript




> // A NON-tail-recursive function.> // The function is not tail> // recursive because the value> // returned by fact(n-1) is used> // in fact(n) and call to fact(n-1)> // is not the last thing done by> // fact(n)> function> fact(n)> {> >if> (n == 0)> >return> 1;> > >return> n * fact(n - 1);> }> // Driver code> document.write(fact(5));> // This code is contributed by divyeshrabadiya07> >

>

>

Wyjście

120>

Złożoność czasowa: NA)
Przestrzeń pomocnicza: NA)

Powyższą funkcję można zapisać jako funkcję rekurencyjną ogonową. Pomysł polega na użyciu jeszcze jednego argumentu i zgromadzeniu wartości silni w drugim argumencie. Gdy n osiągnie 0, zwróć skumulowaną wartość.

Poniżej znajduje się implementacja wykorzystująca funkcję rekurencyjną ogona.

C++




#include> using> namespace> std;> // A tail recursive function to calculate factorial> unsigned factTR(unsigned>int> n, unsigned>int> a)> {> >if> (n <= 1)> >return> a;> >return> factTR(n - 1, n * a);> }> // A wrapper over factTR> unsigned>int> fact(unsigned>int> n) {>return> factTR(n, 1); }> // Driver program to test above function> int> main()> {> >cout << fact(5);> >return> 0;> }>

>

>

Jawa




// Java Code for Tail Recursion> class> GFG {> >// A tail recursive function> >// to calculate factorial> >static> int> factTR(>int> n,>int> a)> >{> >if> (n <=>0>)> >return> a;> >return> factTR(n ->1>, n * a);> >}> >// A wrapper over factTR> >static> int> fact(>int> n) {>return> factTR(n,>1>); }> >// Driver code> >static> public> void> main(String[] args)> >{> >System.out.println(fact(>5>));> >}> }> // This code is contributed by Smitha.>

>

1 do 100 rzymski nr
>

Python3




# A tail recursive function> # to calculate factorial> def> fact(n, a>=>1>):> >if> (n <>=> 1>):> >return> a> >return> fact(n>-> 1>, n>*> a)> # Driver program to test> # above function> print>(fact(>5>))> # This code is contributed> # by Smitha> # improved by Ujwal, ashish2021>

>

>

C#




// C# Code for Tail Recursion> using> System;> class> GFG {> >// A tail recursive function> >// to calculate factorial> >static> int> factTR(>int> n,>int> a)> >{> >if> (n <= 0)> >return> a;> >return> factTR(n - 1, n * a);> >}> >// A wrapper over factTR> >static> int> fact(>int> n) {>return> factTR(n, 1); }> >// Driver code> >static> public> void> Main()> >{> >Console.WriteLine(fact(5));> >}> }> // This code is contributed by Ajit.>

>

>

PHP




// A tail recursive function // to calculate factorial function factTR($n, $a) { if ($n <= 0) return $a; return factTR($n - 1, $n * $a); } // A wrapper over factTR function fact($n) { return factTR($n, 1); } // Driver program to test // above function echo fact(5); // This code is contributed // by Smitha ?>>

>

>

JavaScript




> // Javascript Code for Tail Recursion> // A tail recursive function> // to calculate factorial> function> factTR(n, a)> {> >if> (n <= 0)> >return> a;> > >return> factTR(n - 1, n * a);> }> > // A wrapper over factTR> function> fact(n)> {> >return> factTR(n, 1);> }> // Driver code> document.write(fact(5));> // This code is contributed by rameshtravel07> > >

>

>

Wyjście

120>

Złożoność czasowa: NA)
Przestrzeń pomocnicza: O(1)

Kolejne artykuły na ten temat:

  • Eliminacja Tail Call
  • Optymalizacja wywołań QuickSort Tail (zmniejszenie miejsca w najgorszym przypadku do Log n )