Skip to content

Instantly share code, notes, and snippets.

@junpeitsuji
Last active March 24, 2016 08:13
Show Gist options
  • Save junpeitsuji/9f7823a1f9d55a1fa37f to your computer and use it in GitHub Desktop.
Save junpeitsuji/9f7823a1f9d55a1fa37f to your computer and use it in GitHub Desktop.
面積 n となる直角三角形の辺を発見するプログラム
# 面積 n となる直角三角形の辺を発見するプログラム
require 'rational'
# Rational class にメソッドを追加
class Rational
# 平方数かどうか判定する
def is_square
n = self.numerator
d = self.denominator
sq_n = Math.sqrt(n)
sq_d = Math.sqrt(d)
return (sq_n.floor == sq_n.to_f) && (sq_d.floor == sq_d.to_f)
end
# 平方根を返す
def sqrt
n = self.numerator
d = self.denominator
sq_n = Math.sqrt(n)
sq_d = Math.sqrt(d)
return Rational(sq_n.to_i, sq_d.to_i)
end
end
# 面積が n となる直角三角形を探索する
def find_congruent_triangle n
(1..100).each do |p1|
(1..100).each do |q1|
(1..100).each do |p2|
(1..100).each do |q2|
a = Rational(q1, p1)
b = Rational(q2, p2)
s = a*b/2
# 面積が n かどうか判定
if s.numerator == n*s.denominator then
# ピタゴラスの定理より, c^2 を計算
c_squared = a**2 + b**2
# c^2 が平方数かどうか判定
if c_squared.is_square then
c = c_squared.sqrt
# 見つかったら終了
return [a, b, c]
end
end
end
end
end
end
# みつからなかったら nil を返す
return nil
end
# main part
if __FILE__ == $0
# n = 14 で探索
n = 14
res = find_congruent_triangle(n)
a = res[0]
b = res[1]
c = res[2]
# 結果を出力
puts "a = #{a}, b = #{b}, c = #{c}"
puts ""
# 本当に正しいか確認
puts "(#{a})^2 + (#{b})^2 = #{a*a+b*b} = (#{c})^2"
puts "(#{a})*(#{b})/2 = #{a*b/2} = #{n}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment