Arithmetic/Rational: Difference between revisions
Content added Content deleted
Line 454: | Line 454: | ||
=={{header|Elisa}}== |
=={{header|Elisa}}== |
||
A component for Rational Numbers is defined below. |
|||
<lang Elisa> |
<lang Elisa> |
||
component RationalNumbers; |
component RationalNumbers; |
||
type Rational; |
type Rational; |
||
Line 501: | Line 498: | ||
abs(R) = Rational(abs(R.A), abs(R.B)); |
abs(R) = Rational(abs(R.A), abs(R.B)); |
||
Rational(I) = Rational (I, 1); |
Rational(I) = Rational (I, 1); |
||
Numerator(R) = R.A; |
Numerator(R) = R.A; |
||
Denominator(R) = R.B; |
Denominator(R) = R.B; |
||
Line 509: | Line 504: | ||
<< internal definitions >> |
<< internal definitions >> |
||
Normalize (A = integer, B = integer) -> Rational; |
|||
Normalize (A, B) = [ exception( B == 0, "Illegal Rational Number"); |
|||
Common = GCD(abs(A), abs(B)); |
|||
if B < 0 then Rational(-A / Common, -B / Common) |
|||
else Rational( A / Common, B / Common) ]; |
|||
GCD (A = integer, B = integer) -> integer; |
|||
GCD (A, B) = [ if A == 0 then return(B); |
|||
if B == 0 then return(A); |
|||
if A > B then GCD (B, mod(A,B)) |
|||
else GCD (A, mod(B,A)) ]; |
|||
end component RationalNumbers; |
end component RationalNumbers; |
||
</lang> |
|||
Tests |
|||
<lang Elisa> |
|||
use RationalNumbers; |
|||
PerfectNumbers( Limit = integer) -> multi(integer); |
|||
PerfectNumbers( Limit) = |
|||
[ Candidate = 2 .. Limit; |
|||
Sum:= Rational(1,Candidate); |
|||
[ Divisor = 2 .. integer(sqrt(real(Candidate))); |
|||
if mod(Candidate, Divisor) == 0 then |
|||
Sum := Sum + Rational(1, Divisor) + Rational(Divisor, Candidate); |
|||
]; |
|||
if Sum == Rational(1,1) then Candidate |
|||
]; |
|||
PerfectNumbers(10000)? |
|||
</lang> |
|||
Output |
|||
<lang Elisa> |
|||
6 |
|||
28 |
|||
496 |
|||
8128 |
|||
</lang> |
</lang> |
||