Created
January 2, 2012 05:34
-
-
Save MaulingMonkey/1549482 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Drawing; | |
using System.Drawing.Imaging; | |
using System.Windows.Forms; | |
namespace Ulam { | |
public partial class Form1 : Form { | |
public Form1() { | |
InitializeComponent(); | |
} | |
bool[] NotPrimes = new bool[2]; | |
void RecalculatePrimesUpTo( int limit ) | |
{ | |
var n = limit+1; | |
NotPrimes = new bool[n]; | |
for ( int i=2 ; i<=n/2 ; ++i ) { | |
if (!NotPrimes[i]) { | |
for (int j = 2 * i; j < n; j += i) { | |
NotPrimes[j] = true; | |
} | |
} | |
} | |
} | |
bool IsPrime( int n ) | |
{ | |
if ( NotPrimes.Length <= n ) | |
RecalculatePrimesUpTo(Math.Max(n,2*NotPrimes.Length)); | |
return !NotPrimes[n]; | |
} | |
int ToSpiralN( int x, int y ) | |
{ | |
var ring = Math.Max(Math.Abs(x),Math.Abs(y)); | |
int n = ring * (ring+1) * 4; | |
if ( y == +ring ) n = n - 0*ring + x - ring; | |
else if ( x == -ring ) n = n - 2*ring + y - ring; | |
else if ( y == -ring ) n = n - 4*ring - x + ring; | |
else if ( x == +ring ) n = n - 6*ring - y + ring; | |
else Debug.Fail("Impossible... the balls aren't there!"); | |
return n; | |
} | |
long LongestPaint = 0; | |
unsafe protected override void OnPaint( PaintEventArgs e ) { | |
var w = ClientSize.Width; | |
var h = ClientSize.Height; | |
var stopwatch = new Stopwatch(); | |
stopwatch.Start(); | |
using ( var bitmap = new Bitmap(w,h,PixelFormat.Format32bppArgb) ) | |
{ | |
var bits = bitmap.LockBits( ClientRectangle, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb ); | |
for ( int y=0 ; y<h ; ++y ) | |
{ | |
uint* scanline = (uint*)(bits.Scan0.ToInt64() + y*bits.Stride); | |
for ( int x=0 ; x<w ; ++x ) | |
{ | |
scanline[x] = IsPrime( ToSpiralN( x-w/2, h/2-y )+1 ) ? 0xFF0000FFu : 0xFFB0B0B0u; | |
} | |
} | |
bitmap.UnlockBits(bits); | |
e.Graphics.DrawImage( bitmap, ClientRectangle ); | |
} | |
stopwatch.Stop(); | |
LongestPaint = Math.Max(LongestPaint, stopwatch.ElapsedMilliseconds); | |
Text = "Longest paint took "+LongestPaint+" ms"; | |
base.OnPaint(e); | |
} | |
protected override void OnResize( EventArgs e ) { | |
Invalidate(); | |
base.OnResize(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment