-
Notifications
You must be signed in to change notification settings - Fork 18
/
spiral_matrix.c
61 lines (61 loc) · 1.02 KB
/
spiral_matrix.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
#include<stdio.h>
#include<math.h>
#include<stdint.h>
typedef uint64_t lldu;
int isPrime(lldu n) {
if(n<=1) return 0;
if(n==2) return 1;
if((n&1) == 0) return 0;
int i;
for(i=3;i<=sqrt(n);i+=2) {
if(n%i == 0) return 0;
}
return 1;
}
void generateSpiralMatrix(int n) {
lldu sm[n][n],num = n*n;
int fri = 0,fci=0,lci=n,lri=n,i,j;
while(fri<lri && fci<lci) {
for(i=lci-1;i>=fci;i--) {
sm[lri-1][i] = num--;
}
lri--;
for(i=lri-1;i>=fri;i--) {
sm[i][fci]=num--;
}
fci++;
for(i=fci;i<lci;i++) {
sm[fri][i]=num--;
}
fri++;
for(i=fri;i<lri;i++) {
sm[i][lci-1]=num--;
}
lci--;
}
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
printf("%llu\t",sm[i][j]);
}
printf("\v\n");
}
lldu sum = 0;
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
if( i==j || (i+j) ==n-1) {
lldu temp = sm[i][j];
if(isPrime(temp)) sum+=temp;
}
}
printf("%ju\n", sum);
}
//printf("%ju (0x%jx)\n", sum, sum);
}
int main() {
int t,n,i,j;
scanf("%d",&t);
while(t--) {
scanf("%d",&n);
generateSpiralMatrix(n);
}
}