      INTEGER FUNCTION ICIRLT*8 ( N )
C Count number of lattice points on circle with
C squared radius N
C
C Author: Hugo Pfoertner, http://www.pfoertner.org/
C
C Change history:
C 08.06.2002 Search only in half quadrant
C 04.06.2002 Initial version
      IMPLICIT INTEGER*8 (A-Z)
C Determine nearest integer radius: Convert input to
C 64 bit real and round result of square root to
C nearest integer. This is more robust than to rely
C on exact results of sqrt for exact squares.
C KIDNNT is the DIGITAL Fortran extension of NINT
C REAL*8 -> INTEGER*8
C      IR = NINT ( SQRT ( DBLE ( N ) ) )
      IR = KIDNNT ( SQRT ( DBLE ( N ) ) )
C Preset first point on y-axis
      I = 0
      I2 = 0
      J = IR
      J2 = IR * IR
C M counts hits
      M = 0
C Check if first point is inside circle with r**2=N
      IF ( J2 .LT. N ) THEN
C One step outward
C        WRITE (*,*) J2, '<', N
        J = J + 1
        J2 = J * J
C Check if N is square
      ELSEIF ( J2 .EQ. N ) THEN
C Increase hit counter
        M = 4
C        WRITE (*,*) M, I, J
C To avoid treatment of special case for N=1
C Move 2 right and 1 down
        I = I + 2
        J = J - 1
        I2 = I * I
        J2 = J * J
      ENDIF
C
C Start of search loop
C
10    CONTINUE
C Squared radius of next point
      R2 = I2 + J2
C If point is outside move down
      IF ( R2 .GT. N ) THEN
        J = J - 1
        J2 = J * J
C If point lies on circumference increase hit count
      ELSEIF ( R2 .EQ. N ) THEN
        M = M + 8
C        WRITE (*,*) M, I, J
C Diagonal step 1 right and 1 down
        I = I + 1
        J = J - 1
        I2 = I * I
        J2 = J * J
      ELSE
C Point inside, move right
        I = I + 1
        I2 = I * I
      ENDIF
C Stop criterion: Diagonal of first quadrant (I=J) reached
      IF ( J .LE. I ) THEN
C Check if point on diagonal lies on circumference
        IF ( J .EQ. I .AND. 2*I2 .EQ. N ) THEN
C Add diagonal points
          ICIRLT = M + 4
C          WRITE (*,*) ICIRLT, I, J
        ELSE
C Set function output to accumulated hits
          ICIRLT = M
        ENDIF
C Leave function
        RETURN
      ELSE
C Perform next step of search loop
        GOTO 10
      ENDIF
C End of function ICIRLT
      END
