Fortran Implementation of Problem 4
View source code here on GitHub!
- integer Problem0004/p0004()
1! Project Euler Problem 4
2!
3! I modeled this after the C++ solution, because it was by far the simplest
4!
5! Problem:
6!
7! A palindromic number reads the same both ways. The largest palindrome made from
8! the product of two 2-digit numbers is 9009 = 91 × 99.
9!
10! Find the largest palindrome made from the product of two 3-digit numbers.
11
12module Problem0004
13 implicit none
14contains
15 pure integer function p0004() result(answer)
16 integer :: i, j, k, n, prod, length
17 logical :: is_palindrome
18 character(len=8) :: string
19
20 answer = 0
21 do i = 100, 999
22 do j = 100, 999
23 prod = i * j
24 is_palindrome = .true.
25 write(string, '(I0)') prod
26 length = len_trim(string)
27
28 do k = 1, length
29 n = length - k + 1
30 if (string(k:k) /= string(n:n)) then
31 is_palindrome = .false.
32 exit
33 end if
34 end do
35
36 if (is_palindrome) then
37 answer = max(answer, prod)
38 end if
39 end do
40 end do
41 end function p0004
42end module Problem0004