RosettaCodeData/Task/Hailstone-sequence/D/hailstone-sequence-1.d

24 lines
607 B
D
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
import std.stdio, std.algorithm, std.range, std.typecons;
2013-10-27 22:24:23 +00:00
auto hailstone(uint n) pure nothrow {
2013-04-10 21:29:02 -07:00
auto result = [n];
while (n != 1) {
2015-02-20 00:35:01 -05:00
n = (n & 1) ? (n * 3 + 1) : (n / 2);
2013-04-10 21:29:02 -07:00
result ~= n;
}
return result;
}
void main() {
enum M = 27;
2013-10-27 22:24:23 +00:00
immutable h = M.hailstone;
writeln("hailstone(", M, ")= ", h[0 .. 4], " ... " , h[$ - 4 .. $]);
writeln("Length hailstone(", M, ")= ", h.length);
2013-04-10 21:29:02 -07:00
enum N = 100_000;
2013-10-27 22:24:23 +00:00
immutable p = iota(1, N)
.map!(i => tuple(i.hailstone.length, i))
.reduce!max;
2013-04-10 21:29:02 -07:00
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}