Steven5538

N階階乘運算 - 快速降階法

Word count: 423Reading time: 2 min
2011/11/19 Share

其實是學校作業之一 orz
個人自認自己這個寫得還不錯,所以放出來給大家看看,呵呵。
一般的降階法運算方式應該不用我多說吧:P?
快速降階法大抵是長這樣 –

這個算法最大的問題就是第一個數字不能為0。
下面就是C++的實作範例囉。
獻醜了:P

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <ctime>
#include <iomanip>
#include <cmath>

using namespace std ;

long double determinant (long double ***square , int n , int c) ;

int main()
{
int n , c = 0 ;
long double ***square ;

cout << "Enter the dimension (2 ~ 10): " ;
cin >> n ;
while (n < 2 || n > 10)
{
cout << "Enter the dimension (2 ~ 10): " ;
cin >> n ;
}

cout << "A randomly generated 5-dimensional square matrix:" << endl << endl ;
square = new long double **[n] ; //Dynamic three-dimensional array
for (int i = 0 ; i < n ; i++)
{
square[i] = new long double *[n] ;
for (int j = 0 ; j < n ; j++)
square[i][j] = new long double [n] ;
}

srand(time(NULL)) ;
for (int i = 0 ; i < n ; i++) //random
{
for (int j = 0 ; j < n ; j++)
{
square[i][j][0] = rand() % 10 ;
cout << square[i][j][0] << " " ;
}
cout << endl ;
}
cout << endl ;

cout << determinant (square , n , c) << endl << endl ;

for (int i = 0 ; i < n ; i++) //release
{
for (int j = 0 ; j < n ; j++)
delete []square[i][j] ;
delete []square[i] ;
}
delete []square ;

system("pause") ;
return 0 ;
}

long double determinant (long double ***square , int n , int c) //Fast Reduction Method
{

if (n == 2)
{
return square[0][0][c] * square[1][1][c] - square[1][0][c] * square[0][1][c] ;
}

for (int i = 1 ; i < n ; i++)
{
for (int j = 1 ; j < n ;j++)
square[i - 1][j - 1][c + 1] = (square[0][0][c] * square[i][j][c] - square[i][0][c] * square[0][j][c]) / pow (square[0][0][c],(n - 2)) ;
}

return pow (square[0][0][c],(n - 2) * (n - 2)) * determinant (square , n - 1 , c + 1) ;
}
CATALOG