Matrix chain multiplication: Difference between revisions
Content added Content deleted
SqrtNegInf (talk | contribs) m (→{{header|Perl}}: show cost, as per task spec) |
|||
Line 200: | Line 200: | ||
This is a translation of the Python iterative solution. |
This is a translation of the Python iterative solution. |
||
<lang fortran>module |
<lang fortran>module optim_mod |
||
implicit none |
implicit none |
||
contains |
contains |
||
Line 206: | Line 206: | ||
implicit none |
implicit none |
||
integer :: a(:), n, i, j, k |
integer :: a(:), n, i, j, k |
||
⚫ | |||
integer, allocatable :: u(:, :) |
integer, allocatable :: u(:, :) |
||
⚫ | |||
integer(8), allocatable :: v(:, :) |
integer(8), allocatable :: v(:, :) |
||
n = ubound(a, 1) - 1 |
n = ubound(a, 1) - 1 |
||
allocate (u(n, n), v(n, n)) |
allocate (u(n, n), v(n, n)) |
||
v = |
v = huge(v) |
||
u(:, 1) = -1 |
u(:, 1) = -1 |
||
v(:, 1) = 0 |
v(:, 1) = 0 |
||
Line 219: | Line 219: | ||
do k = 1, j - 1 |
do k = 1, j - 1 |
||
c = v(i, k) + v(i + k, j - k) + int(a(i), 8) * int(a(i + k), 8) * int(a(i + j), 8) |
c = v(i, k) + v(i + k, j - k) + int(a(i), 8) * int(a(i + k), 8) * int(a(i + j), 8) |
||
if ( |
if (c < v(i, j)) then |
||
u(i, j) = k |
u(i, j) = k |
||
v(i, j) = c |
v(i, j) = c |
||
Line 233: | Line 233: | ||
recursive subroutine aux(i, j) |
recursive subroutine aux(i, j) |
||
integer :: i, j, k |
integer :: i, j, k |
||
k = u(i, j) |
k = u(i, j) |
||
if (k < 0) then |
if (k < 0) then |
||
Line 248: | Line 248: | ||
end module |
end module |
||
program |
program matmulchain |
||
use |
use optim_mod |
||
implicit none |
implicit none |
||
call optim([5, 6, 3, 1]) |
|||
call optim([1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]) |
call optim([1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]) |
||
call optim([1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]) |
call optim([1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]) |
||
Line 259: | Line 260: | ||
<pre> |
<pre> |
||
48 (1*(2*3)) |
|||
38120 ((((((((1*2)*3)*4)*5)*6)*7)*(8*(9*10)))*(11*12)) |
38120 ((((((((1*2)*3)*4)*5)*6)*7)*(8*(9*10)))*(11*12)) |
||
1773740 (1*((((((2*3)*4)*(((5*6)*7)*8))*9)*10)*11)) |
1773740 (1*((((((2*3)*4)*(((5*6)*7)*8))*9)*10)*11)) |