This repository was archived by the owner on Nov 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolver_neopt.c
109 lines (105 loc) · 2.36 KB
/
solver_neopt.c
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
* Tema 2 ASC
* 2020 Spring
*/
#include "utils.h"
#define IDX2L(i, j, N) (((i) * (N)) + (j))
/*
* Add your unoptimized implementation here
*/
double* my_solver(int N, double *A, double* B) {
int i, j, k;
/* Calculate the final result in C matrix */
double *C = calloc(N * N, sizeof(double));
if (C == NULL) {
return NULL;
}
/* Calculate the transposed A in At matrix */
double *At = calloc(N * N, sizeof(double));
if (At == NULL) {
return NULL;
}
/* Calculate the B*At part in D */
double *D = calloc(N * N, sizeof(double));
if (D == NULL) {
return NULL;
}
/* Calculate the A * A * B part in E */
double *E = calloc(N * N, sizeof(double));
if (E == NULL) {
return NULL;
}
/* Calculate A * A part in A_square */
double *A_square = calloc(N * N, sizeof(double));
if (A_square == NULL) {
return NULL;
}
/* Calculate the transpose of A matrix */
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if ( i <= j) {
At[IDX2L(j, i, N)] = A[IDX2L(i, j, N)];
}
}
}
/*
* Multiply matrixes B * At, where At is A transposed
* The result is saved in D matrix
*/
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
/*
* At is triangular matrix so we go over
* the elements that give the zero amount.
*/
for (k = j; k < N; k++) {
D[IDX2L(i, j, N)] += B[IDX2L(i, k, N)] * At[IDX2L(k, j, N)];
}
}
}
/*
* Multiply matrixes A * A, where A is triangular matrix
* The result is saved in A_square matrix
*/
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (i <= j) {
for (k = 0; k < N; k++) {
A_square[IDX2L(i, j, N)] += A[IDX2L(i, k, N)] *
A[IDX2L(k, j, N)];
}
}
}
}
/*
* Multiply matrixes A_square * B, where A_square is A * A
* The result is saved in E matrix
*/
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
/*
* A_square is triangular matrix so we go over
* the elements that give the zero amount.
*/
for (k = i; k < N; k++) {
E[IDX2L(i, j, N)] += A_square[IDX2L(i, k, N)] *
B[IDX2L(k, j, N)];
}
}
}
/*
* Add matrixes D + E, where D = B * At, E = A * A * B
* The result is saved in C matrix
*/
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
C[IDX2L(i, j, N)] = D[IDX2L(i, j, N)] + E[IDX2L(i, j, N)];
}
}
free(D);
free(E);
free(A_square);
free(At);
printf("NEOPT SOLVER\n");
return C;
}