-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathulam.c
89 lines (69 loc) · 1.97 KB
/
ulam.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
// source: https://rosettacode.org/wiki/Ulam_spiral_(for_primes)#C
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
typedef uint32_t bitsieve;
unsigned sieve_check(bitsieve *b, const unsigned v)
{
if ((v != 2 && !(v & 1)) || (v < 2))
return 0;
else
return !(b[v >> 6] & (1 << (v >> 1 & 31)));
}
bitsieve* sieve(const unsigned v)
{
unsigned i, j;
bitsieve *b = calloc((v >> 6) + 1, sizeof(uint32_t));
for (i = 3; i <= sqrt(v); i += 2)
if (!(b[i >> 6] & (1 << (i >> 1 & 31))))
for (j = i*i; j < v; j += (i << 1))
b[j >> 6] |= (1 << (j >> 1 & 31));
return b;
}
#define max(x,y) ((x) > (y) ? (x) : (y))
/* This mapping taken from python solution */
int ulam_get_map(int x, int y, int n)
{
x -= (n - 1) / 2;
y -= n / 2;
int mx = abs(x), my = abs(y);
int l = 2 * max(mx, my);
int d = y >= x ? l * 3 + x + y : l - x - y;
return pow(l - 1, 2) + d;
}
/* Passing a value of 0 as glyph will print numbers */
void output_ulam_spiral(int n, const char glyph)
{
/* An even side length does not make sense, use greatest odd value < n */
n -= n % 2 == 0 ? 1 : 0;
const char *spaces = ".................";
int mwidth = log10(n * n) + 1;
bitsieve *b = sieve(n * n + 1);
int x, y;
for (x = 0; x < n; ++x) {
for (y = 0; y < n; ++y) {
int z = ulam_get_map(y, x, n);
if (glyph == 0) {
if (sieve_check(b, z))
printf("%*d ", mwidth, z);
else
printf("%.*s ", mwidth, spaces);
}
else {
printf("%c", sieve_check(b, z) ? glyph : spaces[0]);
}
}
printf("\n");
}
free(b);
}
int main(int argc, char *argv[])
{
const int n = argc < 2 ? 9 : atoi(argv[1]);
output_ulam_spiral(n, 0);
printf("\n");
output_ulam_spiral(n, '#');
printf("\n");
return 0;
}