(* Collection of code snippets by Arne Vajhøj *)
(* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) *)
program BigPowVar;

{$APPTYPE CONSOLE}

uses
  SysUtils;

function numval(c : char) : integer;

begin
   numval := ord(c) - ord('0');
end;

function strval(v : integer) : char;

begin
   strval := chr(ord('0') + v);
end;

function add(v1,v2 : string) : string;

var
   res : string;
   ix1, ix2, tmp, carry : integer;

begin
   res := '';
   carry := 0;
   ix1 := length(v1);
   ix2 := length(v2);
   while (carry > 0) or (ix1 > 0) or (ix2 > 0) do begin
      tmp := carry;
      if(ix1 > 0) then begin
          tmp := tmp + numval(v1[ix1]);
          ix1 := ix1 - 1;
      end;
      if(ix2 > 0) then begin
          tmp := tmp + numval(v2[ix2]);
          ix2 := ix2 - 1;
      end;
      res := strval(tmp mod 2) + res;
      carry := tmp div 2;
   end;
   add := res;
end;

function mulpow2(v : string; pow2 : integer) : string;

var
   res : string;
   i : integer;

begin
   res := v;
   for i := 1 to pow2 do begin
      res := res + '0';
   end;
   mulpow2 := res;
end;

function mulone(v : string; num : integer) : string;

var
   res : string;
   ix, tmp, carry : integer;

begin
   res := '';
   carry := 0;
   ix := length(v);
   while (carry > 0) or (ix > 0) do begin
      tmp := carry;
      if(ix > 0) then begin
          tmp := tmp + num * numval(v[ix]);
          ix := ix - 1;
      end;
      res := strval(tmp mod 2) + res;
      carry := tmp div 2;
   end;
   mulone := res;
end;

function mul(v1,v2 : string) : string;

var
   res : string;
   i : integer;

begin
   res := '0';
   for i := 1 to length(v2) do begin
      res := add(res,mulpow2(mulone(v1,numval(v2[i])),length(v2)-i));
   end;
   mul := res;
end;

function pow(v : string; n : integer) : string;

var
   res : string;
   i : integer;

begin
   res := '1';
   for i := 1 to n do begin
      res := mul(res,v);
   end;
   pow := res;
end;

function fastpow(v : string; n : integer) : string;

var
   res : string;

begin
   writeln(v,' ',n);
   if n=1 then begin
      res := v;
   end else begin
      if odd(n) then begin
         res := mul(v,fastpow(mul(v,v),n div 2));
      end else begin
         res := fastpow(mul(v,v),n div 2);
      end;
   end;
   fastpow := res;
end;

begin
   writeln(pow('2',10));
   writeln(pow('2',100));
   writeln(length(pow('3',1000)));
end.
