c-----------------------------------------------------------
c Chapter 23: The Permanent Function(p217)
c-----------------------------------------------------------
c   Name of subroutine: PERMAN
c
c   Algorithm:Calculate permanent of square matrix.
c
c   input: n=4   
c   complier: f77 perman_2.f nexsub.f
c-----------------------------------------------------------

      parameter(n=4)
      double precision perm, a(n,n), x(n)
      integer in(n)
      do 20 i=1,n
      read (*,10) (a(i,j),j=1,n)
10    format(10(d5.2))
20    continue
      call perman(n,a,in,x,perm)
      write(*,25)
25    format('The permanent of the matrix is')
      write(*,30) perm
30    format(d15.8)
      stop
      end

c-----Subroutine begins here--------------------------------
      subroutine perman(n,a,in,x,perm)
      implicit double precision(a-h,o-z)
      logical mtc
      dimension a(n,n),in(n),x(n)
10    p=0
      n1=n-1
      do 11  i=1,n
      sum=0.
      do 15  j=1,n
15    sum=sum+a(i,j)
11    x(i)=a(i,n)-sum/2.d0
      sgn=-1
20    sgn=-sgn
      prod=sgn
30    call nexsub(n1,in,mtc,ncard,j)
      if(ncard.eq.0) go to 38
      z=2*in(j)-1
      do 35  i=1,n
35    x(i)=x(i)+z*a(i,j)
38    do 39  i=1,n
39    prod=prod*x(i)
      p=p+prod
      if(mtc) go to 20
40    perm=2.*(2*mod(n,2)-1)*p
      return
      end


