Arithmetic/Rational/Ada: Difference between revisions

m
Fixed syntax highlighting.
(moved from Rational Arithmetic)
 
m (Fixed syntax highlighting.)
 
(2 intermediate revisions by 2 users not shown)
Line 1:
<noinclude>{{collection|Rational Arithmetic}}</noinclude>
 
The generic package specification:
<langsyntaxhighlight lang="ada">generic
type Number is range <>;
package Generic_Rational is
Line 61 ⟶ 60:
Zero : constant Rational := (0, 1);
One : constant Rational := (1, 1);
end Generic_Rational;</langsyntaxhighlight>
The package can be instantiated with any integer type. It provides rational numbers represented by a numerator and denominator cleaned from the common divisors. Mixed arithmetic of the base integer type and the rational type is supported. Division to zero raises Constraint_Error. The implementation of the specification above is as follows:
<langsyntaxhighlight lang="ada">package body Generic_Rational is
 
function GCD (A, B : Number) return Number is
Line 284 ⟶ 283:
end Denominator;
 
end Generic_Rational;</langsyntaxhighlight>
The implementation uses solution of the [[greatest common divisor]] task. Here is the implementation of the test:
<langsyntaxhighlight lang="ada">with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
with Ada.Text_IO; use Ada.Text_IO;
with Generic_Rational;
Line 308 ⟶ 307:
end;
end loop;
end Test_Rational;</langsyntaxhighlight>
The perfect numbers are searched by summing of the reciprocal of each of the divisors of a candidate except 1. This sum must be 1 for a perfect number. Sample output:
{{out}}
<pre>
6 is perfect
9,476

edits