Pythagorean triplet

Project Euler again, this time its problem 9.

A Pythagorean triplet is a set of three natural numbers, a<b<c, for which:

$latex a^{2}+b^{2}=c^{2}$

For example:

$latex 3^{2}+4^{2}=9+16=25=5^{2}$.

There exists exactly one Pythagorean triplet for which abc = 1000.
Find the product abc.

My first draft is simply brute force checking:

Module Module1

  Sub Main()
    Dim beganAt As Date = Now

    Dim answer As Integer = pythagorean(1000)

    Dim endAt As Global.System.TimeSpan = Now.Subtract(beganAt)
    Dim took As Integer = endAt.Milliseconds

    Console.WriteLine(answer.ToString + " in " + took.ToString + "ms.")
  End Sub

  Private Function pythagorean(ByVal thisNumber As Integer) As Integer
    For a As Integer = 1 To thisNumber
      For b As Integer = 1 To thisNumber
        For c As Integer = 1 To thisNumber
          If a + b + c = 1000 Then
            If (a * a) + (b * b) = (c * c) Then
              Return (a * b * c)
            End If
          End If
    Return -1
  End Function

End Module

It takes 375 milliseconds but gives the correct answer.


This entry was posted in Coding and tagged , , , . Bookmark the permalink.