電卓を作成する必要があり、その最初の関数が Fatorial であるとしましょう。再帰関数として記述するか、ループを使用して結果を取得できます。再帰は指数関数的な性質のため、より遅いことは誰もが知っています。しかし、行を数えるのではなく、コードでそれを証明するにはどうすればよいでしょうか?
費やされたミリ秒の量を計算しようとしましたが、i7 では、最初の時間とコードが停止するときの間は常にゼロです。
ループと再帰的な方法の間のコードの速度の違いを測定するにはどうすればよいですか?
type
TJanela = class(TForm)
Instrucao: TLabel;
Entrada: TEdit;
Botao: TButton;
procedure Calcular(Sender: TObject);
end;
var
Janela: TJanela;
Val, Fat, Start, TimeRecursive, TimeLoop: Int64;
function FR(N: Int64): Int64; // Fatorial Recursivo
function FL(N: Int64): Int64; // Fatorial em Loop
implementation
{$R *.dfm}
procedure TJanela.Calcular(Sender: TObject);
begin
Val := StrToInt(Entrada.Text);
Start := StrToInt(FormatDateTime('nnsszzz',Now));
Fat := FR(Valor);
TimeRecursive := StrToInt(FormatDateTime('nnsszzz',Now)) - Start;
Start := StrToInt(FormatDateTime('nnsszzz',Now));
Fat := FL(Valor);
TimeLoop := StrToInt(FormatDateTime('nnsszzz',Now)) - Start;
if Val > 25 then
ShowMessage('Delphi can't calculate above [ 25! ]')
else
ShowMessage(' [ ' +
IntToStr(Val) + '! ] is equal to [ ' +
FormatFloat('###,###,###,###,###,###',Fat) + ' ]'#13#13+
'Recursive: [ ' + IntToStr(TimeRecursive) + ' ] ms;'#13+
'Loop: [ ' + IntToStr(TimeLoop) + ' ] ms;');
end;
function FR(N: Int64): Int64;
begin
if N <= 1 then
Result := 1
else
Result := N * FR(N - 1);
end;
function FL(N: Int64): Int64;
var
I: Integer;
begin
for I := 2 to N - 1 do
N := N * I;
if N = 0 then
Result := 1
else
Result := N;
end;
デビッドが答えを出したので、私は数学について質問しました.2つの方程式を導き出し、両方の方法で特定の階乗がコンピューターに費やす時間を決定するのに役立ちます.