module gcd_function
   implicit none

   interface gcd
      module procedure gcd_4, gcd_8, gcd_three_4, gcd_three_8
   end interface

contains

   function gcd_4(a,b)
      implicit none
      integer :: gcd_4
      integer, intent(in) :: a, b
      integer :: l, m, n

      m = a
      n = b

      do
         l = mod(m,n)
         if (l == 0) exit
         m = n
         n = l
      end do

      gcd_4 = n
      return
   end function gcd_4

   function gcd_8(a,b)
      implicit none
      integer(8) :: gcd_8
      integer(8), intent(in) :: a, b
      integer(8) :: l, m, n

      m = a
      n = b

      do
         l = mod(m,n)
         if (l == 0) exit
         m = n
         n = l
      end do

      gcd_8 = n
      return
   end function gcd_8

   function gcd_three_4(a,b,c)
      integer :: gcd_three_4
      integer, intent(in) :: a, b, c

      gcd_three_4 = gcd( gcd(a, b), c)
   end function gcd_three_4

   function gcd_three_8(a,b,c)
      integer(8) :: gcd_three_8
      integer(8), intent(in) :: a, b, c

      gcd_three_8 = gcd( gcd(a, b), c)
   end function gcd_three_8

end module gcd_function

program abc162a
   use gcd_function
   implicit none
   integer :: K, p, q, r
   integer, allocatable :: a(:,:,:)

   read(*,*) K
   allocate(a(k,k,k))

   do r = 1, k
      do q = 1, k
         do p = 1, k
            a(p,q,r) = gcd(p,q,r)
         enddo
      enddo
   enddo

   write(*,*) sum(a(:,:,:))

end program abc162a
