Last active
March 2, 2017 16:39
-
-
Save georgy7/3cfec9340f5864125d9b7f101aa6f0eb to your computer and use it in GitHub Desktop.
Factorial approximation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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