Calculate the Delacorte Number of a square

APL (38)

{.5×+/∊∘.{(∨/Z[⍺⍵])×+/⊃×⍨⍺-⍵}⍨⊂¨⍳⍴Z←⍵}

This is a function that takes a matrix as its right argument, like so:

      sq5←↑(10 8 11 14 12)(21 4 19 7 9)(5 13 23 1 16)(18 3 17 2 15)(24 22 25 6 20)
      sq5
10  8 11 14 12
21  4 19  7  9
 5 13 23  1 16
18  3 17  2 15
24 22 25  6 20
      {.5×+/∊∘.{(∨/Z[⍺⍵])×+/⊃×⍨⍺-⍵}⍨⊂¨⍳⍴Z←⍵}sq5
5957

Explanation:

  • ⊂¨⍳⍴Z←⍵: store the matrix in Z. Make a list of each possible pair of coordinates in Z.
  • ∘.{...}⍨: for each pair of coordinates, combined with each pair of coordinates:
    • +/⊃×⍨⍺-⍵: calculate distance^2: subtract the first pair of coordinates from the second, multiply both by themselves and sum the result
    • ∨/Z[⍺⍵]: get the number in Z for both pairs of coordinates, and find the GCD
    • ×: multiply them by each other
  • +/∊: sum the elements of the result of that
  • .5×: multiply by 0.5 (because we counted each nonzero pair twice earlier)

Python - 128 112 90 89 88

Preparation:

import pylab as pl
from fractions import gcd
from numpy.linalg import norm
from itertools import product

A = pl.array([
    [10,  8, 11, 14, 12],
    [21,  4, 19,  7,  9],
    [ 5, 13, 23,  1, 16],
    [18,  3, 17,  2, 15],
    [24, 22, 25,  6, 20]])

Computing the Delacorte Number (the line that counts):

D=sum(gcd(A[i,j],A[m,n])*norm([m-i,n-j])**2for j,n,i,m in product(*[range(len(A))]*4))/2

Output:

print D

Result:

5957

Mathematica (83 82 79 69 67 66)

Preparation

a={{10,8,11,14,12},{21,4,19,7,9},{5,13,23,1,16},{18,3,17,2,15},{24,22,25,6,20}}

Code

#/2&@@Tr[ArrayRules@a~Tuples~2/.{t_->u_,v_->w_}->u~GCD~w#.#&[t-v]]

If we count using Unicode characters: 62:

Tr[ArrayRules@a~Tuples~2/.{t_u_,v_w_}u~GCD~w#.#&[t-v]]〚1〛/2

Tags:

Math

Code Golf