Hofstadter Q sequence: Difference between revisions

Content added Content deleted
m ({{out}})
(Updated second D entry)
Line 448: Line 448:
<lang d>import std.stdio, std.algorithm, std.range, std.array;
<lang d>import std.stdio, std.algorithm, std.range, std.array;


uint Q(in int n) nothrow
struct Q {
in {
__gshared static Appender!(uint[]) s;
assert(n > 0);
} body {
__gshared static Appender!(int[]) s = [0, 1, 1];


foreach (immutable i; s.data.length .. n + 1)
nothrow static this() {
s ~= [0, 1, 1];
s ~= s.data[i - s.data[i - 1]] + s.data[i - s.data[i - 2]];
return s.data[n];
}

static uint opCall(in int n) nothrow
in {
assert(n > 0);
} body {
foreach (immutable i; s.data.length .. n + 1)
s ~= s.data[i - s.data[i - 1]] + s.data[i - s.data[i - 2]];
return s.data[n];
}
}
}