From 3bcf86dfb00cbbcdf352b4b168c7c517095593c8 Mon Sep 17 00:00:00 2001 From: "R. Tyler Croy" Date: Mon, 14 Mar 2011 20:30:13 -0700 Subject: [PATCH] Add solution to problem nine with python prototype --- nine.adb | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ nine.py | 25 ++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 nine.adb create mode 100644 nine.py diff --git a/nine.adb b/nine.adb new file mode 100644 index 0000000..3e0defc --- /dev/null +++ b/nine.adb @@ -0,0 +1,63 @@ +-- +-- Project Euler problem #9 +-- +-- A Pythagorean triplet is a set of three natural numbers, a < b < c, for +-- which, +-- +-- a^2 + b^2 = c^2 +-- +-- For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. +-- +-- There exists exactly one Pythagorean triplet for which a + b + c = 1000. +-- Find the product abc. + + +with Ada.Numerics.Elementary_Functions, + Ada.Text_IO; + +use Ada.Numerics.Elementary_Functions, + Ada.Text_IO; + +procedure Nine is + Ceiling : constant Natural := 1000; + C : natural := 0; + + function Is_Perfect_Square (Input : in Float) return Boolean is + begin + if Input = Float'Floor (Input) then + return true; + end if; + return false; + end Is_Perfect_Square; + + function Is_Correct_Triplet (A, B, C : in Natural) return Boolean is + begin + if (A + B + C) /= 1000 then + return false; + end if; + + if (A < B) and (B < C) then + return true; + end if; + + return false; + end Is_Correct_Triplet; + +begin + for A in 1 .. Ceiling loop + for B in 1 .. Ceiling loop + declare + C_Squared : constant Natural := (A ** 2) + (B ** 2); + C : constant Float := Sqrt (Float(C_Squared)); + begin + if Is_Perfect_Square (C) and Is_Correct_Triplet (A, B, Natural (C)) then + Put (" A:" & Natural'Image (A)); + Put (" B:" & Natural'Image (B)); + Put (" C:" & Natural'Image (Natural (C))); + New_Line; + Put_Line ("A * B * C =" & Natural'Image (A * B * Natural (C))); + end if; + end; + end loop; + end loop; +end Nine; diff --git a/nine.py b/nine.py new file mode 100644 index 0000000..ae71d53 --- /dev/null +++ b/nine.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python + +import math +import sys + +def main(): + RANGE = 1000 + for a in xrange(RANGE): + for b in xrange(RANGE): + if (a == 0) or (b == 0): + continue + + c_squared = (a ** 2) + (b ** 2) + c = math.sqrt(c_squared) + if not c == math.floor(c): + continue + if (a + b + c) == 1000: + if a < b < c: + print a, b, c + print a * b * c + return 0 + +if __name__ == '__main__': + sys.exit(main()) +