Skip to content

Instantly share code, notes, and snippets.

@georgy7
Last active March 2, 2017 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgy7/3cfec9340f5864125d9b7f101aa6f0eb to your computer and use it in GitHub Desktop.
Save georgy7/3cfec9340f5864125d9b7f101aa6f0eb to your computer and use it in GitHub Desktop.
Factorial approximation
/// License: CC0
import std.math;
real flog10(long n) {
real r = 0;
foreach (i; 1..(n+1)) {
r += log10(i);
}
return r;
}
private immutable int maxExp = cast(int) log10(ulong.max) - 1;
private void print(real e) {
import std.stdio;
import std.array;
if (e < maxExp) {
real r = pow(10.0, e);
writeln(cast(ulong) r);
} else {
// Not sure, it's always correct.
real shortPart = e % maxExp;
real r = pow(10.0, shortPart);
writeln(cast(ulong) r, "0".replicate(cast(int) (e - shortPart)));
}
}
void main() {
print(flog10(1));
print(flog10(10));
print(flog10(100));
print(flog10(8000));
}
/*
$ time rdmd flog.d
real 0m0.308s
user 0m0.260s
sys 0m0.040s
# on i5-4460
$ /usr/bin/time -v ./flog |& grep resident
Maximum resident set size (kbytes): 2388
Average resident set size (kbytes): 0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment