[Shootout-list] Nsieve bits Ada bench

Pascal Obry pascal@obry.net
Sat, 19 Mar 2005 17:12:35 +0100


Here is the nsieve-bits Ada bench. I'd like to point out that
such a program is really clean in Ada. The only difference
from the nsieve standard bench is: "pragma Pack (Boolean_Array);"
The access to the array is done as if the array was not packed
(one boolean by word). The compiler generates the necessary
code to access individual bits.

If you want to check that I'm not cheating you can output the
size of the array object in Count with:

   Put_Line ("Size = " & Integer'Image (S'Size));

-- $Id$
-- http://dada.perl.it/shootout/
-- Contributed by Pascal Obry on 2005/03/19

with Ada.Command_Line;    use Ada.Command_Line;
with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Nsieve_Bits is

   function Count (M : in Natural) return Natural is
      type Boolean_Array is array (2 .. M) of Boolean;
      pragma Pack (Boolean_Array);
      C : Natural := 0;
      S : Boolean_Array := (others => True);
      I : Positive;
   begin
      for K in S'Range loop
         if S (K) then
            C := C + 1;
            I := K * 2;
            while I <= M loop
               S (I) := False;
               I := I + K;
            end loop;
         end if;
      end loop;
      return C;
   end Count;

   procedure Run (N : in Natural) is
      M : Natural;
   begin
      M := 2 ** N * 10_000;
      Put ("Primes up to ");
      Put (Item => M, Width => 8);
      Put (Item => Count (M), Width => 8);
      New_Line;
   end Run;

   N : constant Natural := Natural'Value (Argument (1));
begin
   Run (N);
   Run (N - 1);
   Run (N - 2);
end Nsieve_Bits;

Pascal.

-- 

--|------------------------------------------------------
--| Pascal Obry                           Team-Ada Member
--| 45, rue Gabriel Peri - 78114 Magny Les Hameaux FRANCE
--|------------------------------------------------------
--|              http://www.obry.org
--| "The best way to travel is by means of imagination"
--|
--| gpg --keyserver wwwkeys.pgp.net --recv-key C1082595