IDENTIFICATION DIVISION.
PROGRAM-ID. 167D.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
  SELECT STDIO ASSIGN TO KEYBOARD. 
*>
DATA DIVISION.
FILE SECTION.
FD STDIO.
01 INP        PIC X(1400000).
*>
WORKING-STORAGE SECTION.
01 INW        PIC  X(30).
01 N          PIC  9(06).
01 KX         PIC  X(19).
01 K          PIC  9(18).
01 LP         PIC  9(18).
01 SH         PIC  9(18).
01 AMR        PIC  9(06).
01 P1         PIC  9(07) COMP.
01 P2         PIC  9(07) COMP.
01 I          PIC  9(06) COMP.
01 TBL.
   03 A       PIC  9(06) OCCURS 200000.
   03 B       PIC  9(06) OCCURS 200000.
01 X          PIC  9(06).
01 SA         PIC  9(06).
01 OUT        PIC  Z(05)9.
*> 
PROCEDURE DIVISION.
  ACCEPT INW.
  UNSTRING INW DELIMITED BY ' '
      INTO N KX.
  IF (KX = '1000000000000000000')
    MOVE 999999999999999999 TO K
  ELSE
    MOVE KX TO K
  END-IF.
*>
  OPEN INPUT STDIO.
  READ STDIO.
  CLOSE STDIO.
*>
  MOVE ZERO TO TBL.
  MOVE 1 TO P1.
  PERFORM VARYING I FROM 1 BY 1 UNTIL I > N
    PERFORM VARYING P2 FROM P1 BY 1 UNTIL INP(P2:1) = ' '
    END-PERFORM
    MOVE INP(P1:P2 - P1) TO A(I)
    COMPUTE P1 = P2 + 1
  END-PERFORM.
*>
  MOVE A(1) TO X.
  PERFORM VARYING I FROM 1 BY 1 UNTIL I > K OR B(X) > 0 OR X = 1
    MOVE I    TO B(X)
    MOVE A(X) TO X
  END-PERFORM.
*>
  COMPUTE SA = I - B(X).
  COMPUTE LP = K - B(X)
  IF (KX = '1000000000000000000')
    ADD 1 TO LP
  END-IF.
*>
  DIVIDE LP BY SA GIVING SH REMAINDER AMR.
*>
  IF (B(X) = 0 OR B(X) > K) 
    MOVE 1 TO X
    MOVE K TO AMR
  END-IF.
  PERFORM VARYING I FROM 1 BY 1 UNTIL I > AMR
    MOVE A(X) TO X
  END-PERFORM.
*>
  MOVE X TO OUT.
  DISPLAY FUNCTION TRIM(OUT).
  STOP RUN.
