Skip to content

Instantly share code, notes, and snippets.

@shotarok
Created February 27, 2014 16:57
Show Gist options
  • Save shotarok/9254249 to your computer and use it in GitHub Desktop.
Save shotarok/9254249 to your computer and use it in GitHub Desktop.
Uram Spiral from wikipeda http://en.wikipedia.org/wiki/Ulam_spiral.
#include <iostream>
#include <cstring>
using namespace std;
const int N = 30;
const int LENGTH = 2*N+1;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, -1, 0, 1};
bool feald[LENGTH][LENGTH];
bool is_prime[LENGTH*LENGTH];
void sieve_of_eratosthenes() {
memset(is_prime, true, sizeof(feald));
is_prime[0] = false, is_prime[1] = false;
for (int i = 2; i < LENGTH*LENGTH; ++i) {
if (is_prime[i]) {
for (int j = 2; i * j < LENGTH*LENGTH; ++j) {
is_prime[i*j] = false;
}
}
}
}
void make_ulam_spiral() {
int step = 1, cnt = 1, dir = 0;
int x = N, y = N;
while (cnt <= LENGTH*LENGTH) {
for (int k = 0; k < 2; ++k) {
for (int i = 0; i < step; ++i) {
feald[y][x] = is_prime[cnt++];
x += dx[dir];
y += dy[dir];
}
dir = (dir + 1) % 4;
}
++step;
}
return;
}
void output() {
for (int i = 0; i < LENGTH; ++i) {
for (int j = 0; j < LENGTH; j++) {
cout << (feald[i][j] ? "*" : ".");
}
cout << endl;
}
}
int main() {
sieve_of_eratosthenes();
make_ulam_spiral();
output();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment