Segment violation (was Re: Why I could not cast string to int?)

Timon Gehr timon.gehr at gmx.ch
Thu Feb 2 14:18:25 PST 2012


On 02/02/2012 05:28 PM, xancorreu wrote:
> I get "segment violation" error with ./factorial 400000
> How can I resolve it?
>
> My code is:
>
> import std.stdio, std.bigint, std.string, std.conv, std.stream;
>
> BigInt recFactorial(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(std.conv.to!int(args[1])));
> } catch {
> writeln("Error");
> }
> }
>
>
>
> Thanks a lot,

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

BigInt factorial(int n) {
     BigInt result=1;
     foreach(i;1..n) result*=i;
     return result;
}

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


More information about the Digitalmars-d-learn mailing list