# HW4

unknown
java
19 days ago
2.8 kB
2
Indexable
Never
```import java.util.Scanner;

public class Main {
static void function(double[][] A, int n){
for(int row = 0 , col = 0; col < n ; col++){
// A[row][col] == 0  -> 找到其他row在此col不是0的交換
if(Math.abs(A[row][col]) <= 1e-9){ // A[row][col] == 0
for(int i = row + 1 ; i < n ; i++){
if(Math.abs(A[i][col]) > 1e-9){ // A[row][col] > 0
double[] temp = A[row];
A[row] = A[i];
A[i] = temp;
break;
}
}
}

// 交換完後還是0 -> 直接到下一個col
if(Math.abs(A[row][col]) <= 1e-9)
continue;

for(int i = row + 1 ; i < n ; i++){
double f = A[i][col] / A[row][col];
for(int j = col ; j <= n ; j++){
A[i][j] -= f * A[row][j];
}
}
row++;
}
}

static String determine(double[][] A, int n){
int Rank1 = n , Rank2 = n;
for(int i = 0 ; i < n ; i++){
boolean allVarZero = true;
for(int j = 0 ; j < n ; j++){
if(Math.abs(A[i][j]) > 1e-9){ // A[row][col] != 0
allVarZero = false;
break;
}
}
if(allVarZero)
Rank1--;
if(allVarZero && Math.abs(A[i][n]) <= 1e-9)
Rank2--;
}
/*
System.out.println("Rank1 : " + Rank1);
System.out.println("Rank2 : " + Rank2);
*/
if(Rank2 > Rank1)
return "No solution";
else if(n > Rank2)
return "Infinite solutions";
else
return "The only solution";
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();
double[][] A = new double[n][n + 1];

int r = 0;
while(scanner.hasNextDouble()){
double input = scanner.nextDouble();
if(input == -999)
break;
A[r][0] = input;
for(int c = 1 ; c <= n ; c++)
A[r][c] = scanner.nextDouble();
r++;
}

function(A , n);
/*
for(int i = 0 ; i < n ; i++){
for(int j = 0 ; j < n+1 ; j++){
System.out.print(A[i][j]);
System.out.print(" ");
}
System.out.print("\n");
}
*/
String ans = determine(A , n);
System.out.println(ans);
}
}```