Fortran Implementation of Problem 9

View source code here on GitHub!

integer Problem0009/p0009()
 1! Project Euler Problem 9
 2!
 3! This was pretty fun to port
 4!
 5! Problem:
 6!
 7! A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
 8! a**2 + b**2 = c**2
 9!
10! For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
11!
12! There exists exactly one Pythagorean triplet for which a + b + c = 1000.
13! Find the product abc.
14
15module Problem0009
16    implicit none
17contains
18    integer function p0009() result(answer)
19        integer :: a, b, c, a_square, b_square, c_square
20        c = 3
21
22        do
23            c_square = c * c
24
25            do b = 2, c
26                b_square = b * b
27
28                do a = 1, b
29                    a_square = a * a
30
31                    if (a_square + b_square == c_square .and. a + b + c == 1000) then
32                        answer = a * b * c
33                        return
34                    end if
35                end do
36            end do
37            c = c + 1
38        end do
39    end function p0009
40end module Problem0009

Tags: pythagorean-triple