//
// main.cpp
// 2015 New Start
//
// Created by zr9558 on 13/2/15.
// Copyright (c) 2015 zr9558. All rights reserved.
//
#include <iostream>
using namespace std;
#include<math.h>
// Algorithm 5.1 (Evaluation of determinant using partial pivoting), Algorithm Det_Partial_Pivoting.
const double eps=1e-10;
int max1( double b[],int k, int n) // return the index of maximum value from b[k] to b[n-1]
{
double max=fabs(b[k]);int index=k;
for( int i=k; i!=n; ++i)
{
if(fabs(b[i])>max) { index=i; max=b[i];}
}
return index;
}
int main()
{
double a[100][100], b[100];// Calculate the determinant of the matrix a;
int sign=1, n;
cout<<"Enter the size of the matrix"<<endl;
cin>>n;
cout<<"Enter the Matrix"<<endl;// input the matrix;
for( int i=0; i!=n; ++i)
for( int j=0; j!=n; ++j)
cin>>a[i][j];
for(int k=0; k!=n; ++k)
{
for( int i=k; i!=n; ++i) b[i]=a[i][k];
int j=max1(b,k,n);
if( fabs(a[j][k])<eps)exit(0);
if( j!=k) // if j!=k, then interchange the kth and jth rows and set sign=-sign; else exit the loop;
{
sign*=-1;// sign indicates the sign of the determinant when interchanges two rows;
for( int i=k; i!=n; ++i)
{
double temp=a[j][i]; a[j][i]=a[k][i]; a[k][i]=temp;
}
}
for(int j=k+1; j!=n; ++j)// Subtract a[j][k]/a[k][k] times the kth row from the jth row for j=k+1, k+2,..., n-1. This step makes a[k+1][k], a[k+2][k],..., a[n-1][k] zero.
{
double t1=a[j][k]/a[k][k];
for( int i=0; i!=n; ++i)
a[j][i]-=t1*a[k][i];
}
}
double Value=sign;
for( int i=0; i!=n; ++i)
Value*=a[i][i];
cout<<"The Determinant is "<<Value<<endl;
return 0;
}