Write a program that uses a recursive algorithm to compute the determinant of a
ID: 3680096 • Letter: W
Question
Write a program that uses a recursive algorithm to compute the determinant of a matrix (If you refer to a Linear Algebra text, you may find the minors are called co-factors). It should read a matrix, print it out, compute, and print the determinant. Your program should be able to evaluate multiple matrices on a single execution. For class purposes, your program should handle matrices up to and including those of order 6. In a real application, the sizes could be much larger. You are required to use an array for this problem. Your solution must be recursive.
Justify your data structures. Consider an iterative implementation. Would it be more efficient? What data structures would you choose in that case?
As a minimum, use the following eight matrices to test your program, formatted as shown to the right.
SAMPLE INPUT
1
5
2
2 3
5 9
3
3 -2 4
-1 5 2
-3 6 4
4
2 4 5 6
0 3 6 9
0 0 9 8
0 0 0 5
4
2 4 5 6
0 0 0 0
0 0 9 8
0 0 0 5
4
2 0 0 0
0 3 0 0
0 0 9 0
0 0 0 5
4
2 4 0 6
1 3 0 0
4 0 0 8
2 5 0 5
6
6 4 6 4 6 4
1 2 3 4 5 6
6 5 4 3 2 1
3 2 3 2 3 2
4 6 4 6 4 6
1 1 1 1 1 1
Explanation / Answer
import java.util.Scanner.*;
public class Determinant
{
double A[][];
double m[][];
int N;
int start;
int last;
public Determinant (double A[][], int N, int start, int last){
this.A = A;
this.N = N;
this.start = start;
this.last = last;
}
public double[][] generateSubArray (double A[][], int N, int j1){
m = new double[N-1][];
for (int k=0; k<(N-1); k++)
m[k] = new double[N-1];
for (int i=1; i<N; i++)
{
int j2=0;
for (int j=0; j<N; j++)
{
if(j == j1)
continue;
m[i-1][j2] = A[i][j];
j2++;
}
}
return m;
}
public double determinant(double A[][], int N)
{
double res;
if (N == 1)
res = A[0][0];
else if (N == 2)
res = A[0][0]*A[1][1] - A[1][0]*A[0][1];
else
{
res=0;
for (int j1=0; j1<N; j1++)
{
m = generateSubArray (A, N, j1);
res += Math.pow(-1.0, 1.0+j1+1.0) * A[0][j1] * determinant(m, N-1);
}
}
return res;
}
}
if (N == 1)
res = A[0][0];
else if (N == 2)
res = A[0][0]*A[1][1] - A[1][0]*A[0][1];
else
{
res=0;
for (int j1=0; j1<N; j1++)
{
m = generateSubArray (A, N, j1);
res += Math.pow(-1.0, 1.0+j1+1.0) * A[0][j1] * computeDeterminant(m, N-1);
}
}
return res;
}
public static void main(String args[])
{
double res;
ForkJoinPool pool = new ForkJoinPool();
ParallelDeterminants d = new ParallelDeterminants();
d.inputData();
long starttime=System.nanoTime();
res = pool.invoke (d);
long EndTime=System.nanoTime();
System.out.println("the determinant valaue is " + res);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.