← 都来码 / Dolaima← 例程索引ada/primes.adb原文

ada/primes.adb · 1326 字节 · 下载原文

-- 素数筛:压「数组声明/下标读写 + 子程序(function / procedure)+ while/for 嵌套」。
--
-- 这是本子集的能力边界样本:一维数组、**一基下标**(Ada 是 1..N)、
-- 函数返回整数、过程无返回、过程内部调用函数。

with Ada.Text_IO; use Ada.Text_IO;

procedure Primes is
   type Flags is array (1 .. 50) of Integer;
   Sieve : Flags;

   function Is_Prime(N : Integer) return Integer is
      K : Integer := 2;
   begin
      if N < 2 then
         return 0;
      end if;
      while K * K <= N loop
         if N mod K = 0 then
            return 0;
         end if;
         K := K + 1;
      end loop;
      return 1;
   end Is_Prime;

   -- 过程:把 1..50 的素性填进全局数组。过程体里调用上面的函数。
   procedure Fill is
   begin
      for I in 1 .. 50 loop
         Sieve(I) := Is_Prime(I);
      end loop;
   end Fill;

   Count : Integer := 0;
begin
   Fill;

   for I in 1 .. 50 loop
      if Sieve(I) = 1 then
         Count := Count + 1;
      end if;
   end loop;

   Put_Line("primes_below_50=" & Integer'Image(Count));

   -- 前 5 个素数逐个打出来(应为 2 3 5 7 11)
   for I in 1 .. 11 loop
      if Sieve(I) = 1 then
         Put(Integer'Image(I) & " ");
      end if;
   end loop;
   New_Line;
end Primes;