What does recursion vs iteration look like in roblox lua?
Code samples would be ideal
What does recursion vs iteration look like in roblox lua?
Code samples would be ideal
The same in any language.
Here is an example for the factorial of a number. (n! = n * (n - 1) * (n - 2) .. 1)
Iterative:
local function Factorial(N)
local Product = 1
for I = 2, N do
Product = Product * I
end
return Product
end
Recursive:
local function Factorial(N)
if (N == 1) then
return N
end
return N * Factorial(N - 1)
end
Which one would you say is faster?
The first because the second makes more function calls.
A long time ago someone told me Roblox does not have a tail-call optimization, so I assume it would be even slower then. I’m not sure about the validity of that claim though.
Alright sounds good thanks for the information
I tested to see. The iterative method is much faster. (This is not Roblox, but the stats will be similar)
But only by a margin though, you wouldnt even notice
So I guess if it’s for a simple code and you’re trying to be fancy you would go with recursive
Yeah. Maybe if the function was more expensive to compute though, you would want to be careful. This is a basic factorial.
Well about the simple part I guess you got that right but about the fancy part nah
Well, it was a joke… most people normally use iteration because it’s easier to understand and that’s what you normally learn at the beginning - that’s why I called it “fancy”.
Oh sorry I didnt get it LOL, well Im gonna try using recursion and see how that goes
Recursion is “better” depending on what you’re doing. If you’re doing something like the fibonacci sequence, which is inherently recursive, it makes sense to use recursion because the code will be easier to write.
(Of course there is an iterative solution, but to me it is less intuitive)
Yeah Ive always used iterative and its always whats pushed on you when you start programming so Im gonna try to use recursion for some smaller things that might not take up alot of memory
Can you show me the fibonacci example (Recursive)?
Like what’s the input and what’s the output?
This is in c++
( recursive )
fyi i didnt write this
#include<bits/stdc++.h>
using namespace std;
int fib(int n)
{
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
int main ()
{
int n = 9;
cout << fib(n);
getchar();
return 0;
}
The definition of the f(n) term of the fibonacci sequence is f(n - 2) + f(n - 1) where f(1) = 0.
0 1 1 2 3 5 8 13 21 34 …
0 + 1 = 1;
1 + 1 = 2;
1 + 2 = 3;
2 + 3 = 5;
3+ 5 = 8;
5 + 8 = 13
That’s actually pretty clever… I think I’ll get into recursive stuff more since I never experimented with it much.
Thanks!
(Replying to both of you lol)
Iteration is always faster and you should opt for it whenever possible. It consumes less memory, and is faster. However, it makes the code longer and in hindsight, it could never fully practically replace recursion, where n of cases is indefinite.