Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Faster tests with a fast pythagorean-triplet example #262

Merged
merged 1 commit into from
Sep 29, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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