How to check for a prime number in Delphi

后端 未结 2 569
暖寄归人
暖寄归人 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<Integer>;
      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.

    0 讨论(0)
  • 2021-01-17 07:15

    procedure TForm1.btnprimeClick(Sender: TObject); var K, I, iCount : Integer; begin for K := iStart to iEnd do begin iCount := 0; for I := 2 to iEnd do begin if K mod I = 0 then begin Inc(iCount); end; end; if iCount = 1 then begin memData.Lines.Add(IntToStr(K)); end; end; end;

    0 讨论(0)
提交回复
热议问题