Al 02/02/12 19:30, En/na bearophile ha escrit:
xancorreu:

I get "segment violation" error with  ./factorial 400000
How can I resolve it?
You are having a stack overflow. DMD currently doesn't print a good message 
because of this regression that is being worked on:
http://d.puremagic.com/issues/show_bug.cgi?id=6088

On Windows with DMD you increase the stack like this:
dmd -L/STACK:100000000 -run test2.d 400000>  result.txt

If it goes in overflow still, increase the stack some more. But it will take a 
long time to compute the result even with the latest 2.058head with improved GC 
because the algorithm you have used to compute the factorial is very bad.


I have rewritten your code like this:

import std.stdio, std.bigint, std.conv, std.exception;

BigInt recFactorial(in int n) {
     if (n == 0)
         return BigInt(1);
     else
         return BigInt(n) * recFactorial(n - 1);
}

void main(string[] args) {
     if (args.length != 2) {
         writeln("Factorial requires a number.");
     } else {
         try {
            writeln(recFactorial(to!int(args[1])));
         } catch (ConvException e) {
            writeln("Error");
         }
     }
}


Note the usage of ConvException, it's a very good practice to never use a generic 
"gotta catch them all" expression, because it leads to hiding other bugs in 
your code, and this is a source for troubles.

Bye,
bearophile
Thank you very much for recode this. But you "only" put a "in" in recFactorial function argument. What this mean? **Why** this is more efficient than mine?

For the other hand, how can increase the stack in linux?


Thanks,
Xan.

Reply via email to