program main
    implicit none
    integer k, a, b, c
    integer :: total = 0
    read *, k

    do a=1, k
        do b = 1, k
            do c = 1, k
                total = total + euclid(a, euclid(c, b))
            enddo
        enddo
    enddo
    print *, total

contains
    integer function euclid(a, b)
        integer, intent(in) :: a,b
        integer bigger, smaller, rem

        if ( a < b ) then
            bigger = b
            smaller = a
        else
            bigger = a
            smaller = b
        endif

        do
            rem = mod(bigger, smaller)
            if ( rem == 0 ) then
                euclid = smaller
                exit
            else
                bigger = smaller
                smaller = rem
            endif
        enddo
    end function
end program main
