Segfault games with factorials

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 24 07:36:58 PDT 2014


On Thu, Jul 24, 2014 at 01:14:40PM +0000, Darren via Digitalmars-d-learn wrote:
> I have the following code in fac.d (modified from the factorial
> examples on RosettaCode):
> 
> #!/usr/bin/rdmd
> import std.bigint;
> 
> pure BigInt factorial(BigInt n) {
>     static pure BigInt inner(BigInt n, BigInt acc) {
>     	return n == 0 ? acc : inner(n - 1, acc * n);
>     }
>     return inner(n, BigInt("1"));
> }
> 
> void main(string[] args) {
> 	import std.stdio;
> 	BigInt input = args[1];
> 	writeln(factorial(input));
> 	return;
> }
> 
> It (more or less consistently) on my machine will calculate 'fac
> 47610', and (more or less consistently) will core dump with a segfault
> on 'fac 47611'.
[...]

You're probably running out of stack space because of your recursive
function. Write it as a loop instead, and you should be able to go
farther:

	pure BigInt factorial(BigInt n) {
		auto result = BigInt(1);
		while (n > 1)
			result *= n;
		return result;
	}


T

-- 
Ignorance is bliss... until you suffer the consequences!


More information about the Digitalmars-d-learn mailing list