using System; using System.CodeDom; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication4 { class Program { private static void Main(string[] args) { var m = new int[,] { {1, 2, 3, 4}, {2, 1, 1, 1}, {3, 1, 2, 1}, {4, 1, 1, 1}, }; Console.WriteLine(GetDeterminant(m)); m = new int[,] { {1, 2, 3, 4,5,1, 2, 3, 4,5,}, {2, 1, 1, 1,3,1, 2, 3, 4,5,}, {3, 1, 2, 1,8,1, 2, 3, 4,5,}, {4, 1, 1, 1,1,1, 2, 3, 4,5,}, {4, 10, 1, 2,1,1, 2, 3, 4,5,}, {1, 2, 3, 4,5,1, 2, 3, 4,5,}, {2, 1, 1, 1,3,1, 2, 3, 4,5,}, {3, 1, 2, 1,8,1, 2, 3, 4,5,}, {4, 1, 1, 1,1,1, 2, 3, 4,5,}, {4, 10, 1, 2,1,1, 2, 3, 4,5,}, }; Console.WriteLine(GetDeterminant(m)); } private static void NextPermutation(int[] permutation, ref bool isPositive) { int lenght = permutation.Length, firstIndex = 0, secondIndex; for (int i = 0; i < lenght - 1; i++) if (permutation[i] < permutation[i + 1]) firstIndex = i; secondIndex = lenght-1; while (permutation[firstIndex] > permutation[secondIndex]) secondIndex--; swapInArray(permutation, firstIndex, secondIndex); var count = (lenght - firstIndex-1) / 2; for (int i = 1; i <= count; i++) swapInArray(permutation, firstIndex + i, lenght - i); if (count%2 == 0) isPositive = !isPositive; } private static void swapInArray(int[] array, int firstIndex, int secondIndex) { var temp = array[firstIndex]; array[firstIndex] = array[secondIndex]; array[secondIndex] = temp; } static int GetDeterminant(int[,] matrix) { var rang = matrix.GetLength(0); if(rang != matrix.GetLength(1)) // fatal error throw new Exception("Bad matrix"); if (rang == 1) return matrix[0, 0]; var indexes = new int[rang]; var countOfPermutation = 1; for (int i = 0; i < rang; i++) { indexes[i] = i; countOfPermutation *= (i + 1); } int determinant = 0, multiplication; bool isPositive = true; for (int i = 0; i < countOfPermutation; i++) { multiplication = 1; for (int j = 0; j < rang; j++) multiplication *= matrix[j, indexes[j]]; determinant += multiplication * (isPositive?1:-1); NextPermutation(indexes,ref isPositive); } return determinant; } } }