繁体   English   中英

前 n 个素数的 Eratosthenes 筛分法

[英]Sieve of Eratosthenes for first n prime numbers

我试图让我的 Eratosthenes 筛选程序只输出用户请求的前 n 个素数。 Sieve 自己工作得很好 - 它正确输出前 100 个素数(如下面的数组所示),但最后一个循环中的计数器变量工作不正常,我不知道为什么。 例如,如果用户为 n 输入“5”,则只会打印前 3 个素数。

有人可以帮我找出我的错误吗? 我的意图是让“count”成为一个非常简单的计数器,每次递增 1,直到达到 n。

int n;
cout << "Enter the number of primes you want to print:\n";
cin >> n;

int arr[100] {0};

for (int i = 2; i <= sqrt(100); i++)
{
    if (arr[i] == 0)
    {
        for (int j = 2; i*j<100; j++)
            arr[j*i] = 1;
    }
}

for (int i = 3, count = 0; i <= 100 && count != n; i++, count++)
{
    if (arr[i] == 0)
        cout << i << '\n';
}

你应该只计算素数,而不是所有的数字。

还应该更正循环的i范围。 第一个质数是2 ,元素arr[100]不可用。

for (int i = 2, count = 0; i < 100 && count != n; i++) // don't increment count here
{
    if (arr[i] == 0)
    {
        cout << i << '\n';
        count++; // count a prime number here
    }
}

我有一个使用 Ada 的解决方案,它可能会给您一些帮助。 我创建了一个名为 Is_Prime 的函数,当传递给它的参数是素数时返回 TRUE,否则返回 FALSE。

以下是包含 Is_Prime 声明的包规范。 将包规范视为类似于 C 头文件。

package Primality is
   function Is_Prime(Num : Positive) return Boolean;
end Primality;

该函数的实现在包体中,大致对应于一个 C .c 文件。

-----------------------------------------------------------------------
-- Primality Body                                                    --
-----------------------------------------------------------------------
with Ada.Numerics.Generic_Elementary_Functions;

package body Primality is
   function Is_Prime (Num : Positive) return Boolean is
      package Flt_Funcs is new Ada.Numerics.Generic_Elementary_Functions
        (Float);
      use Flt_Funcs;

      T      : Integer          := 2;
      Limit  : constant Integer := Integer (Sqrt (Float (Num)));
      Result : Boolean          := True;
   begin
      if Num = 2 then
         Result := True;
      else
         while T <= Limit loop
            if Num mod T = 0 then
               Result := False;
               exit;
            end if;
            T := T + (if T > 2 then 2 else 1);
         end loop;
      end if;
      return Result;
   end Is_Prime;
end Primality;

Ada 允许程序员随意命名“主”文件。 以下是允许用户指定要输出的素数数量的“主”文件。

with primality; use primality;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;


procedure List_Primes is
   count : Natural;
   Num   : Positive := 2;
begin
   Put("Enter the number of primes you want to print: ");
   Get(count);
   while count > 0 loop
      if Is_Prime(Num) then
         Put_Line(Num'Image);
         count := count - 1;
      end if;
      Num := Num + (if Num = 2 then 1 else 2);
   end loop;
end List_Primes;

示例运行的输出是:

Enter the number of primes you want to print: 20
 2
 3
 5
 7
 11
 13
 17
 19
 23
 29
 31
 37
 41
 43
 47
 53
 59
 61
 67
 71

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM