Thursday, July 21, 2011

Limit of Recursion!

Recently I was going through Linked in Delphi user's group and found that few programming sections in a programming site needs examples in Delphi to demonstrate the methodology of implementing solution to a problem in various languages. On visiting the site I found that there is a need of particular example to find - Limit of Recursion as implemented in the language. This is a very interesting question as we all use recursion for implementing various solutions but we rarely care to find the actual limit to which we can implement recursion. Although most of this problems answer depends on the memory available to particular systems however we still can check this limit by implementing a very basic recursive function.

The idea behind this simple program is to keep on iterating and visit nest level for a recursive function till the time we go out of memory. So the limiting condition here is the draining of the memory. A simple program like the following will demonstrate this limit -


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Level : integer;
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

function Recursive(Level : integer) : integer;
begin
try
Level := Level + 1;
Recursive(Level);
except on e: Exception do
Result := Level;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage('Level = ' + inttostr(Level));
ShowMessage('Level = ' + inttostr(Recursive(Level)));
end;

end.

This program takes up an integer value and tries to increment the value and call the function till StackOverflow error occurs and then simply prints this value. This implementation gave the following result on my Windows Vista 64 bit computer for integer value - 4375221. The values can differ if we take int64 instead of signed integer in the above example.

No comments: