-
-
Notifications
You must be signed in to change notification settings - Fork 70
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
pythagorean-triplet: Faster tests with a fast example (#262)
This shaves 25% off the test time for me.
- Loading branch information
Showing
1 changed file
with
24 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |