Skip to content

Instantly share code, notes, and snippets.

@DavidColby
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidColby/11240533 to your computer and use it in GitHub Desktop.
Save DavidColby/11240533 to your computer and use it in GitHub Desktop.
Method for finding pythagorean triples in a given range. Returns the triple with the largest sum that is less than the given perimeter
def find_biggest_triple(perimeter)
all_triples = [] # Empty array to hold all of the triplets
max_side_length = perimeter/2 # This isn't necessary because we filter but the method runs a lot faster if we cut down how many times the all_triples loops need to run. a + b should always be greater than c so no need to build triples that won't be selected
# Run outer loop perimeter/2 times - This is our hypotenuse
max_side_length.times do |a|
a.times do |b|
b.times do |c|
# Pythagorean triplet is found if the square of the two shorter sides (the two interior loops) equals the square of the hypotenuse
if c**2 + b**2 == a**2
# If sides are less than perimeter, add to triples array
if c + b + a < perimeter
all_triples << [a,b,c]
end
end
end
end
end
# The each method below breaks if biggest_triple isn't initalized to 0 here.
biggest_triple = [0]
all_triples.each do |nums|
biggest_triple = nums if biggest_triple.inject(:+) < nums.inject(:+)
end
biggest_triple #=> Largest triplet in the given range
end
@sdevani
Copy link

sdevani commented May 1, 2014

Good work! You could optimize it by calculating the last of the triplets (given a and b) and checking if the 3rd number would be an integer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment