!
! Double-base palindromes
!
! Problem 36
!
! The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
!
! Find the sum of all numbers, less than one million, which are palindromic in
! base 10 and base 2.
!
! (Please note that the palindromic number, in either base, may not include
! leading zeros.)
!
program double_base_palindromes
    implicit none
    integer, parameter :: max_number = 1000000

    call solver

    contains

    function number_to_string(num, base) result(str)
        integer, intent(in) :: num
        integer, optional, intent(in) :: base
        character(:), allocatable :: str
        character(:), allocatable :: fmt
        character(256) :: template
        integer :: b

        b = 10
        if (present(base)) b = base
        allocate(fmt, source='')
        str = template
        select case (b)
        case (2)
            fmt = '(b0)'
        case (10)
            fmt = '(i0)'
        case default
            error stop
        end select
        write(str, fmt) num
        str = trim(str)
    end function number_to_string

    function test_palindromic(str) result(result)
        character(*), intent(in) :: str
        logical :: result
        integer :: n, i

        n = len(str)
        result = .false.
        do i = 1, n / 2
            if (str(i:i) /= str(n-i+1:n-i+1)) return
        end do
        result = .true.
    end function test_palindromic

    subroutine solver
        integer :: i, sum
        character(:), allocatable :: n_10, n_2

        sum = 0
        do i = 1, max_number
            n_10 = number_to_string(i, 10)
            n_2 = number_to_string(i, 2)
            if (.not. test_palindromic(n_10)) cycle
            if (.not. test_palindromic(n_2)) cycle
            sum = sum + i
            print *, n_10, ', ', n_2
        end do
        print *, 'result =', sum
    end subroutine

end program double_base_palindromes