recursive function n=n+1 in JS?

What is the code for a basic unityscript recursive loop? say n=n+1.

for example this is JS for factorial, how does it go in unityscript?

function factorial (n)
{ 
    if(n==0) return(1);

    return (n * factorial (n-1) );
}
print(factorial(5));

eg Factorial(8) = 8! = 8* 7* 6* 5* 4* 3* 2* 1 = 40320

3 Answers

3

I think it wants you to explicitly declare the return type in a recursive function.

function factorial (n) : int
{ 
    if(n==0) return(1);

    return (n * factorial (n-1) );
}


print(factorial(5));

Thanks! i didnt find "return" in the unity reference only things like "onkey.return" so i thought it might be something different, and also the "if" has no curly brackets after it so i was totally out of my depth. interestingly, factorial 1.2 crashes unity, unity just dissapears... so it must be an infinite feedback loop? and factorial 13 is out of range of int32..

1.2 is a float. And that's technically allowed but, you should probably add a type to n so that doesn't happen. function factorial (n : int) : int { that way no one can pass a float and get an infinity loop.

I suggest making that int unsigned. (uint). I can still pass -1 to that and crash it.

Just make that conditional a <= and we don't have to worry about any of this and we can move on. if( n <= 0) return 1;

for those of you learning JS etc, there are no unity tuts on unity recursive, so here are recursive functions and links for learning:

Factorial Complete:

var number = 5.5;

function factorial(n) : int
{

// If the number is not an integer, round it down. 
n = Mathf.Floor(n);

// The number must be equal to or bigger than zero 
if (n < 0)
{
    return (0);
}

if ((n == 0) || (n == 1))
{ // If the number is 0 or 1, its factorial is 1.
    return (1);
}
else 
{ // Make a recursive call 
    return (n * factorial(n - 1)); 
} 
}

print(factorial(number));

Fibonacci in unity:

function Fibo(n) : int
{
if((n==1)||(n==2)) return 1;
else return Fibo(n-1) + Fibo(n-2);
}

print(Fibo(8));


good page for JS recursion, in the end i think they do a JS maze generator!

http://www.siteexperts.com/tips/functions/ts20/page1.asp

The comment and edit buttons from this page have dissapeared on chrome. i found a unity tree generator code!

link text