PROGRAM PowerFinder;

{Declarations module}
CONST Terminal = 11;  {max. number of terminal digits}
TYPE Number = ARRAY[1..Terminal] OF INTEGER;
VAR Rot, Digits, RightDigits, DigitsLeft : INTEGER;
    Power : LONGINT;
    LastDigits : Number; {array to hold the 'terminal' digits}
    Fits : BOOLEAN;  {test variable to ensure terminal digits fit the pattern}

BEGIN {program}
	
	{Initialization module - includes display of column headings}
	WRITELN('Significant Digits               Power             Terminal Digits');
	WRITELN;
	Power := 0; RightDigits := 1; DigitsLeft := RightDigits;
	FOR Rot := 1 TO Terminal DO			{initialize array to all 0's}
		LastDigits[Rot] := 0;
	LastDigits[1] := 1;	{put first value in array}
	
REPEAT
	FOR Digits := DigitsLeft TO Terminal DO
		BEGIN {loop}
			
			Rot := 1; Fits := FALSE;  {re-initialize variables for each loop iteration}
			
			{Array test module}
			REPEAT
				Fits := ((LastDigits[Rot] = 1) OR (LastDigits[Rot] = 2));
				Rot := Rot + 1;
			UNTIL ((NOT (Fits)) OR (Rot > Digits));
			
			{Display module}
			IF (Fits) THEN
				BEGIN
					WRITE('       ', RightDigits:2, '                   ');
					WRITE(Power:10, '                   ');
					
					{Display array in correct order}
					FOR Rot := RightDigits DOWNTO 1 DO
						WRITE(LastDigits[Rot]:1);
						
					WRITELN;	{advance to next line to prepare for next answer}
					
					{increment value of RDigits every time an answer is found/displayed}
					RightDigits := RightDigits + 1;
				END;  {  }
		END; {loop}
		
	{Array Doubling/Carrying module}
	FOR Rot := 1 TO Terminal DO
		LastDigits[Rot] := LastDigits[Rot] + LastDigits[Rot];
	FOR Rot := 1 TO Terminal DO
		IF (LastDigits[Rot] > 9) THEN
			BEGIN  {  }
				LastDigits[Rot] := LastDigits[Rot] - 10;  {subtract excess to carry}
				
				IF (Rot < Terminal) THEN  {if not on last digit then carry over 1}
					LastDigits[Rot + 1] := LastDigits[Rot + 1] + 1;
			END;
	
	{Calculate new 'Power' of 2 being tested}
	Power := Power + 1;
	
	{Decrement amount of checking to be done when an answer has been found}
	DigitsLeft := RightDigits;

UNTIL (RightDigits > Terminal);  {loop until all 'terminal' digits have been found}

END. {program}