Arithmetic/Rational: Difference between revisions

Line 3,738:
{{incomplete|TI-89 BASIC}}
While TI-89 BASIC has built-in rational and symbolic arithmetic, it does not have user-defined data types.
 
=={{header|zkl}}==
Enough of a Rational class for this task (ie implement the testing code "nicely").
<lang zkl>class Rational{ // Weenie Rational class, can handle BigInts
fcn init(_a,_b){ var a=_a, b=_b; normalize(); }
fcn toString{
if(b==1) a.toString()
else "%d//%d".fmt(a,b)
}
var [proxy] isZero=fcn{ a==0 };
fcn normalize{ // divide a and b by gcd
g:= a.gcd(b);
a/=g; b/=g;
if(b<0){ a=-a; b=-b; } // denominator > 0
self
}
fcn abs { a=a.abs(); self }
fcn __opNegate{ a=-a; self } // -Rat
fcn __opAdd(n){
if(Rational.isChildOf(n)) self(a*n.b + b*n.a, b*n.b); // Rat + Rat
else self(b*n + a, b); // Rat + Int
}
fcn __opSub(n){ self(a*n.b - b*n.a, b*n.b) } // Rat - Rat
fcn __opMul(n){
if(Rational.isChildOf(n)) self(a*n.a, b*n.b); // Rat * Rat
else self(a*n, b); // Rat * Int
}
fcn __opDiv(n){ self(a*n.b,b*n.a) } // Rat / Rat
fcn __opEQ(r){ // Rat==Rat, Rat==n
if(Rational.isChildOf(r)) a==r.a and b=r.b;
else b==1 and a==r;
}
}</lang>
<lang zkl>foreach p in ([2 .. (2).pow(19)]){
sum,limit := Rational(1,p), p.toFloat().sqrt();
foreach factor in ([2 .. limit]){
if(p%factor == 0) sum+=Rational(1,factor) + Rational(factor,p);
}
if(sum.b==1) println("Sum of recipr. factors of %6s = %s exactly%s"
.fmt(p, sum, (sum==1) and ", perfect." or "."));
}</lang>
{{out}}
<pre>
Sum of recipr. factors of 6 = 1 exactly, perfect.
Sum of recipr. factors of 28 = 1 exactly, perfect.
Sum of recipr. factors of 120 = 2 exactly.
Sum of recipr. factors of 496 = 1 exactly, perfect.
Sum of recipr. factors of 672 = 2 exactly.
Sum of recipr. factors of 8128 = 1 exactly, perfect.
Sum of recipr. factors of 30240 = 3 exactly.
Sum of recipr. factors of 32760 = 3 exactly.
Sum of recipr. factors of 523776 = 2 exactly.
</pre>
Anonymous user