#=

  Euler #44 in Julia.

  Problem 44:
  """
  Pentagonal numbers are generated by the formula, P(n)=n(3n−1)/2.
  The first ten pentagonal numbers are:

  1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...

  It can be seen that P(4) + P(7) = 22 + 70 = 92 = P(8). However,
  their difference,  70 − 22 = 48, is not pentagonal.

  Find the pair of pentagonal numbers, P(j) and P(k), for which their sum
  and difference is pentagonal and D = |P(k) − P(j)| is minimised; what
  is the value of D?
  """

  This Julia program was created by Hakan Kjellerstrand, hakank@gmail.com
  See also my Julia page: http://www.hakank.org/julia/

=#

include("Euler.jl")

# 0.04571280s
function euler44a()
    s = (1:2500).|>n->floor(Int,n*(3*n-1) / 2)
    t = Set(s)
    d = 10_000_000
    for j in s
        for k in s
            a = j+k
            b = abs(j-k)
            if j < k &&
                a < d &&
                a in t &&
                b < d &&
                b in t

                d = b
                break
            end
        end
    end

    return d
end

# 0.04486643s
function euler44b()
    n = 2500
    s = (1:2500).|>n->floor(Int,n*(3*n-1) / 2)
    t = Set(s)
    d = 10_000_000

    for j in 1:n
        for k = 1:n
            if s[j] >= s[k]
                continue;
            end
            a = s[j]+s[k]
            if a >= d
                continue
            end
            b = abs(s[j]-s[k])
            if b >= d
                continue
            end
            if a in t && b in t
                d = b
                break
            end
        end
    end

    return d
end

# run_euler(euler44a)
run_euler(euler44b)
