Convert SM3.0 to SM2.0?

Traditional factorial (e.g. fact(x) = { 1 if x = 0 else x * fact(x-1) } ) isn't fully tail recursive, so no dice. (the x * return_value happens after the call to fact() ) You can rewrite it so it is tail recursive however. :)
 
DemoCoder said:
Traditional factorial (e.g. fact(x) = { 1 if x = 0 else x * fact(x-1) } ) isn't fully tail recursive, so no dice. (the x * return_value happens after the call to fact() ) You can rewrite it so it is tail recursive however. :)

Err I think you are allowed to assume that multiplication is commutative :)
 
It doesn't matter, you have

Code:
fact(x)
  if (x == 0) return 1;
  else
    return x * fact(x-1);

becomes (with temporaries inserted)

fact(x)
  if(x == 0) return 1;
  else
    t = fact(x-1);
    return x * t;

does matter if you return x * t or t * x. Tail recursion requires that the very last operation be a tail-call, not the "next to last" operation. :)

The extra temporary 't' takes stack space, which will grow without bound.

You can rewrite as so:
Code:
fact(x, acc) 
    if (x == 0) return acc;
    else return fact(x - 1, x * acc);

Now it's tail recursive.
 
I was unsure of whether max loops supported was 2^8 or 2^16. Of course, you can emulate higher than 2^8 by using nested loops. Thus, the max PS3.0 limit is 2^8*2^8*2^8*2^8 = 2^32 = 4 billion iterations.
 
Back
Top