Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Whether this is tail recursion depends on how the code is compiled.</p> <p>Tail recursion happens when you're directly returning a call to another function (possibly yourself). Tail call optimization (the reason people care about tail recursion) happens when the compiler/interpreter notices this, and just replaces the current stack frame rather than creating another. In your case, if it is compiled naively, you don't have tail recursion because you're making the recursive call, then assigning it to a variable in your call stack, which you later return. That assignment step means that you're doing additional stuff after calling the other function, which makes your code as it stands not a candidate for tail call optimization.</p> <p><em>However</em> a good compiler should rewrite your code like so:</p> <pre><code>int takeModulusTAILRECURSION(int coef, int x, int n, int module){ if ( n &gt; 0 ) return takeModulusTAILRECURSION( mod(coef * x, module), x , n - 1, module ); else if ( n == 0) return mod ( coef , module ); else return 0; } //take modul of an integer ( both negative and positive ) int mod(int x, int modul){ while ( x &lt; 0) x += modul; return x % modul; } </code></pre> <p>Now it is tail recursive.</p> <p>But whether tail call optimization could happen now depends on the language and implementation. For example if your code is supposed to be Java, then as <a href="https://stackoverflow.com/questions/105834/does-the-jvm-prevent-tail-call-optimizations">Does the JVM prevent tail call optimizations?</a> points out, you aren't going to get tail call optimization no matter what you do.</p> <p><em>Edit</em>: I was saying "tail recursive" for "tail recursive and tail call optimized".</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload