Anonymous user
Arithmetic/Rational: Difference between revisions
Improved and updated D entry
(Updated D entry) |
(Improved and updated D entry) |
||
Line 368:
=={{header|D}}==
<lang d>import std.bigint, std.traits, std.conv;▼
▲<lang d>import std.bigint, std.traits;
T gcd(T)(/*in*/ T a, /*in*/ T b) /*pure nothrow*/ {
// std.numeric.gcd doesn't work with BigInt.
return (b != 0) ? gcd(b, a % b) : (a < 0) ? -a : a;
}
Line 380 ⟶ 379:
}
BigInt toBig(T)(in ref T n) pure nothrow if (isIntegral!T) {▼
return BigInt(n);▼
▲struct Rational {
▲ /*const*/ private BigInt num, den; // numerator & denominator
private enum Type { NegINF = -2,
Line 395 ⟶ 388:
PosINF = 2 };
this(U :
num = n.num;
den = n.den;
Line 401 ⟶ 394:
this(U)(in U n) pure nothrow if (isIntegral!U) {
num =
den = 1UL;
}
this(U, V)(/*in*/ U n, /*in*/ V d) /*pure nothrow*/ {
num =
den =
/*const*/
if (common != 0) {
num /= common;
Line 416 ⟶ 409:
den = 0;
}
if (den < 0) { //
num = -num;
den = -den;
Line 422 ⟶ 415:
}
}
T result = n;
return result;
}
T nomerator() /*const*/ pure nothrow @property {
return num;
}
return den;
}
Line 437 ⟶ 439:
return ((num < 0) ? "-" : "+") ~ "infRat";
}
return
}
/*const pure nothrow*/ if (op == "+" || op == "-") {
return
}
/*const pure nothrow*/ if (op == "*") {
return
}
/*const pure nothrow*/ if (op == "/") {
return
}
/*const pure nothrow*/ if (isIntegral!
op == "-" || op == "*" || op == "/")) {
return opBinary!op(
}
/*const pure nothrow*/ if (op == "^^") {
return
}
/*const pure nothrow*/ if (isIntegral!
return
}
/*const pure nothrow*/ {
mixin("this = this " ~ op ~ "l;");
return this;
}
RationalT opUnary(string op)()
/*const pure nothrow*/ if (op == "+" || op == "-") {
return
}
bool opCast(
return num != 0;
}
int opEquals(
if (type() == Type.NaRAT || rhs.type() == Type.NaRAT)
return false;
Line 491 ⟶ 498:
}
int opCmp(
auto rhs =
if (type() == Type.NaRAT || rhs.type() == Type.NaRAT)
throw new Exception("Compare
if (type() != Type.NORMAL ||
rhs.type() != Type.NORMAL) // for infinite
return (type() == rhs.type()) ? 0 :
((type() < rhs.type()) ? -1 : 1);
return (diff == 0) ? 0 : ((diff < 0) ? -1 : 1);
}
Line 512 ⟶ 519:
}
alias Rational = RationalT!BigInt;
version (arithmetic_rational_main) { // test part▼
void main() {▼
import std.stdio, std.math;▼
foreach (p; 2 .. 2 ^^ 19) {▼
▲ void main() {
▲ import std.stdio, std.math;
if (p % factor == 0)▼
▲ foreach (immutable p; 2 .. 2 ^^ 19) {
sum = sum + Rational(1, factor) + Rational(factor, p);▼
▲ if (p % factor == 0)
if (sum.denominator == 1)
p, sum, (sum == 1) ? ", perfect." : ".");
}
}
}</lang>
Use the <code>-version=rational_arithmetic_main</code> compiler switch to run the test code.
{{out}}
▲Sum of recipr. factors of 120 = 2 exactly.
<pre>Sum of recipr. factors of 6 = 1 exactly, perfect.
Sum of recipr. factors of 28 = 1 exactly, perfect.
Line 550 ⟶ 549:
Sum of recipr. factors of 32760 = 3 exactly.
Sum of recipr. factors of 523776 = 2 exactly.</pre>
Currently RationalT!BigInt is not fast.
=={{header|Elisa}}==
|