RosettaCodeData/Task/Exponentiation-operator/D/exponentiation-operator.d

48 lines
1 KiB
D
Raw Permalink Normal View History

2013-04-10 16:57:12 -07:00
import std.stdio, std.conv;
struct Number(T) {
2015-02-20 00:35:01 -05:00
T x; // base
2013-04-10 16:57:12 -07:00
alias x this;
string toString() const { return text(x); }
Number opBinary(string op)(in int exponent)
2015-02-20 00:35:01 -05:00
const pure nothrow @nogc if (op == "^^") in {
2013-04-10 16:57:12 -07:00
if (exponent < 0)
assert (x != 0, "Division by zero");
} body {
debug puts("opBinary ^^");
int zerodir;
T factor;
if (exponent < 0) {
zerodir = +1;
2015-02-20 00:35:01 -05:00
factor = T(1) / x;
2013-04-10 16:57:12 -07:00
} else {
zerodir = -1;
factor = x;
}
T result = 1;
int e = exponent;
while (e != 0)
if (e % 2 != 0) {
result *= factor;
e += zerodir;
} else {
factor *= factor;
e /= 2;
}
return Number(result);
}
}
void main() {
alias Double = Number!double;
writeln(Double(2.5) ^^ 5);
alias Int = Number!int;
writeln(Int(3) ^^ 3);
writeln(Int(0) ^^ -2); // Division by zero.
}