%mathpiper,def="GammaConstNum"

GammaConstNum() :=
[
  Local(k, n, A, B, U'old, U, V'old, V, prec, result);
  prec:=BuiltinPrecisionGet();
  NonN([
    BuiltinPrecisionSet(prec+IntLog(prec,10)+3);	// 2 guard digits and 1 to compensate IntLog
    n:= 1+Ceil(prec*0.5757+0.2862);	// n>(P*Ln(10)+Ln(Pi))/4
    A:= -Internal'LnNum(n);
    B:=1;
    U:=A;
    V:=1;
    k:=0;
    U'old := 0;	// these variables are for precision control
    V'old := 0;
    While(U'old-U != 0 Or V'old-V != 0)
    [
     k++;
     U'old:=U;
     V'old:=V;
     // B:=N( B*n^2/k^2 );
     B:=MultiplyNum(B,n^2/k^2);	// slightly faster
     // A:=N( (A*n^2/k+B)/k );
     A:=MultiplyNum(MultiplyNum(A,n^2/k)+B, 1/k);	// slightly faster
     U:=U+A;
     V:=V+B;
    ];
    If(InVerboseMode(), Echo("GammaConstNum: Info: used", k, "iterations at working precision", BuiltinPrecisionGet()));
    result:=DivideN(U,V);	// N(U/V)
  ]);
  BuiltinPrecisionSet(prec);	// restore precision
  RoundTo(result, prec);	// return correctly rounded result
];

%/mathpiper