program A062845;
uses crt;
var n,f:qword;b:array[0..40] of byte;d:array[0..40] of qword;i:byte;c:char;
{The number n will be the current one subject to checking, and the number f
will be the corresponding function value f(n). Any b[i] will be 0 or 1, and
the following equalities will hold:
n=b[0]+b[1]2+b[2]2^2+···+b[40]2^40, f=b[0]+b[1]3+b[2]3^2+···+b[40]3^40.
For any i in [0..40], the value 3^i-(1+3+3^2+···+3^(i-1)) will be assigned to
d[i], thus f(n+1)=f(n)+d[i] will hold when b[0]=b[1]=···=b[i-1]=1 and b[i]=0.}

procedure compute_directly;
var q:qword;
begin
 q:=n;for i:=0 to 40 do begin b[i]:=q mod 2;q:=q div 2 end;
 if q>0 then
  begin
   writeln('The argument value should not exceed 2199023255551');{2199023255551=2^41-1}
   halt
  end;
 f:=0;for i:=40 downto 0 do f:=b[i]+3*f;
end;

procedure interruptor;
begin
 if keypressed and (upcase(readkey)='I') then
  begin
   write('Last checked: ',n);
   repeat c:=readkey until (upcase(c)='R') or (upcase(c)='A');
   if upcase(c)='R' then begin write(#13);clreol end else halt
  end
end;

begin
 writeln('For any non-negative integer n, let f(n) be the one whose base 3');
 writeln('representation has the same sequence of digits as the binary one');
 writeln('of the number n. The present program consecutively looks for and');
 writeln('displays non-negative integers n less than 2^41 such that f(n) is');
 writeln('a multiple of n. The start number for the search can be arbitrarily');
 writeln('chosen in this range. The search can be temporarily interrupted by');
 writeln('pressing the I-key. Then the last value of n will be displayed that');
 writeln('has been already checked, and you may resume the search or abort it');
 writeln('by pressing the R-key or the A-key, respectively.');
 d[0]:=1;for i:=0 to 39 do d[i+1]:=3*d[i]-1;
 write('    Please enter the start number: ');readln(n);
 compute_directly;
 if (f=0) or (f mod n=0) then writeln(n);
 while n<2199023255551 do
  begin
   i:=0;while b[i]=1 do begin b[i]:=0;i:=i+1 end;b[i]:=1;;
   n:=n+1;f:=f+d[i];
   if f mod n=0 then writeln(n);
   interruptor
  end;
 writeln('Search completed.')
end.