How to check for a prime number in Delphi

后端 未结 2 566
暖寄归人
暖寄归人 2021-01-17 06:57

I want to read all prime numbers between 1 and 10000 into a dynamic array and all non-prime numbers into another dynamic array and then read the prime array into riche

2条回答
  •  囚心锁ツ
    2021-01-17 07:04

    Perhaps the main problem you have is that you mix all the different aspects (looping over candidates, prime checking, display etc.) into a single function.

    Life becomes much easier if you decompose the task into small pieces that just perform a single task. Start with a function to test if a number is prime.

    function IsPrime(N: Integer): Boolean;
    var
      M: Integer;
    begin
      Assert(N > 0);
      if N = 1 then // annoying special case
      begin
        Result := False;
        exit;
      end;
      for M := 2 to (N div 2) do
      begin
        if N mod M = 0 then
        begin
          Result := False;
          exit;
        end;
      end;
      Result := True;
    end;
    

    Now you might wish to make a list containing primes:

    var 
      Primes: TList;
      N: Integer;
    ....
    // create Primes
    for N := 1 to 10000 do
      if IsPrime(N) then
        Primes.Add(N);
    

    This is not the most efficient way to enumerate primes. But it's probably where you should start and I've mainly written this answer to encourage you to separate code into small logical methods that do specific focused tasks.

提交回复
热议问题