Welcome to the Second Life Forums Archive

These forums are CLOSED. Please visit the new forums HERE

Finding a factorial with LSL

Very Keynes
LSL is a Virus
Join date: 6 May 2006
Posts: 484
12-29-2007 08:33
Hi,

Anybody have a simple LSL function to find a Factorial, I can't find anything in the wiki or library. If not I guess i'll have to write one but im not sure how efficiant I can make it :)
JayDee Unknown
Registered User
Join date: 13 Nov 2005
Posts: 175
12-29-2007 08:42
http://wiki.secondlife.com/wiki/LSL_Portal[\url]

Probably have to make one. Add it if you do.
_____________________
Ace Cassidy
Resident Bohemian
Join date: 5 Apr 2004
Posts: 1,228
12-29-2007 10:04
a factorial function is a classic recursive function :

integer factorial(integer n)
{
if ( n == 1 )
return(1);
else return( n * factorial(n-1) );
}

You may run out of stack space with large values of n... If that is a potential problem, then use the more straightforward, but certainly less elegant :

integer factorial(integer n)
{
integer i;
integer product = 1;

for( i = n; i > 1; i-- )
product = product * i;

return ( product );
}
_____________________
"Free your mind, and your ass will follow" - George Clinton
Very Keynes
LSL is a Virus
Join date: 6 May 2006
Posts: 484
12-29-2007 10:52
Thanks Ace,
I was worried about useing the recursive method as I have seen warnings about ressursion in LSL, however, this is what I tried.

CODE

integer fact(integer x)
{
if (x <= 1)
{
return 1;
}
else
{
return x * fact (x - 1);
}
}

default
{
state_entry()
{
llListen(PUBLIC_CHANNEL,"",NULL_KEY,"");
}
listen(integer channel, string name, key id, string message)
{
llOwnerSay((string)fact((integer)message));
}
}
CODE


to my supprise it worked and was a reasonable speed but the range was not good.
I then used a modified version of your second code like this

CODE

float fact(integer n)
{float product = 1;for( ; n > 1; n-- ) product = product * n;
return product;}

default
{
state_entry()
{
llListen(PUBLIC_CHANNEL,"",NULL_KEY,"");
}
listen(integer channel, string name, key id, string message)
{
llOwnerSay((string)fact((integer)message));
}
}
CODE


To my absalute amazement it has a greater range than my calulator which overflows at !69, so I can't validate the results but it apeares to work up to !170 returned value is 7257415615308000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
!171 returns Infinity :) lsl is more powerfull than i give it credit for some times.

Thanks Ace :)