Skip to content

Commit

Permalink
pythagorean-triplet: Faster tests with a fast example (#262)
Browse files Browse the repository at this point in the history
This shaves 25% off the test time for me.
  • Loading branch information
cmcaine authored Sep 29, 2020
1 parent 6adc8ef commit 87e24ce
Showing 1 changed file with 24 additions and 10 deletions.
34 changes: 24 additions & 10 deletions exercises/pythagorean-triplet/example.jl
Original file line number Diff line number Diff line change
@@ -1,13 +1,27 @@
function pythagorean_triplets(input)
triplets = []
for a in 1:(ceil(input/2))
for b in a:(ceil((input-a)/2))
c = input - a - b
triplet = sort([a, b, c])
if (triplet[1]^2 + triplet[2]^2 == triplet[3]^2)
push!(triplets, Tuple(Int.(triplet)))
end
"""
pythagorean_triplets(n)
Find all positive integer triplets `(a, b, c)` s.t. `a + b + c = n` and `a < b < c` and `a^2 + b^2 == c^2`.
"""
# cmcaine's answer, with thanks to akshu3398.
function pythagorean_triplets(n)
triplets = NTuple{3, Int}[]
# Lower bound because the smallest triple is 3, 4, 5.
# Upper bound implied by a < b < c && a + b + c == n.
for a in 3:cld(n, 3) - 1
# Derived by eliminating c from these simultaneous
# equations and solving for b:
# a^2 + b^2 = c^2
# a + b + c = n
b = (n^2 - 2n * a) / (2 * (n - a))
if a < b && isinteger(b)
c = n - a - b
# Proof that b < c:
# Let b = c. Then a^2 + b^2 = c^2 ≡ a^2 = 0 but we know that a ≠ 0.
# Let b > c. a^2 + b^2 = c^2 ≡ a^2 = c^2 - b^2.
# If b > c, a^2 < 0, but that is impossible for real numbers.
push!(triplets, (a, b, c))
end
end
return(unique(triplets))
return sort!(triplets)
end

0 comments on commit 87e24ce

Please sign in to comment.