Euler Solution 39

From ProgSoc Wiki

Jump to: navigation, search

Solutions for Problem 39

If p is the perimeter of a right angle triangle, {a, b, c}, which value, for p ≤ 1000, has the most solutions?

Ruby by tomchristmas

Runtime: 51.699s (on kali) (AARGH!).

OK, the real problem is 'what is the largest number of Pythagorean triad sums that are equal to p?', so I nicked my solution to Problem 9 (from outer space ;) and retooled it slightly, so that I could consider a range of solutions, rather than just one number. It's ugly, it's brute force, but it works!

greatest_solution = 0
p = 0

12.upto(1000){|x|
  puts x
  solutions = 0
 
  1.upto(x/2){|c|
    1.upto((x/2) - 1){|b|
      a = x - b - c 
      solutions += 1 if c ** 2 == a ** 2 + b ** 2
    }
  }

  if solutions > greatest_solution
     greatest_solution = solutions
     p = x
  end
}

puts "#{p} - #{greatest_solution} solutions"
Personal tools