Skip to content

Instantly share code, notes, and snippets.

@berenoguz
Last active August 29, 2015 14:16
Show Gist options
  • Save berenoguz/e6530f34bfa16641d343 to your computer and use it in GitHub Desktop.
Save berenoguz/e6530f34bfa16641d343 to your computer and use it in GitHub Desktop.
Ulam Spiral written to PNG
/**
* Ulam Spiral
* http://en.wikipedia.org/wiki/Ulam_spiral
* @author Beren Oguz
* @copyright 2015, Beren Oguz
* @license This code is licensed with BSD-2 clause License
* Please see: http://opensource.org/licenses/BSD-2-Clause
*/
#include <cstdint>
#include <cmath>
#include <png++/png.hpp>
static constexpr const char* file_name = "ulam-spiral.png";
static constexpr std::size_t image_width = 500;
static constexpr std::size_t image_height =500;
typedef std::uintmax_t Natural;
bool is_prime(Natural num)
{
if(num==0 || num==1)
{
return false;
}
else if(num==2 || num==3)
{
return true;
}
Natural root = std::sqrt(num);
for(Natural x=2; x<=root; x++)
{
if(num%x == 0)
{
return false;
}
}
return true;
}
int main()
{
png::image<png::rgb_pixel> image(image_width, image_height);
Natural size = 1;
Natural current = 1;
bool count = 1;
Natural nums=1;
char direction = 0;
for(std::size_t y = image_height/2; nums < image_height*image_width;)
{
for(std::size_t x = image_width/2; nums < image_height*image_width;)
{
if(is_prime(nums))
{
image[x][y] = png::rgb_pixel(0,0,0);
}
else
{
image[x][y] = png::rgb_pixel(255,255,255);
}
nums++;
current--;
if(current == 0)
{
if(count)
{
count = false;
current = size;
}
else
{
count = true;
current = size;
size++;
}
if(direction!=3)
{
direction++;
}
else
{
direction = 0;
}
}
switch(direction)
{
case 0:
x++;
break;
case 1:
y--;
break;
case 2:
x--;
break;
case 3:
y++;
break;
}
}
}
image.write(file_name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment