atom0s Moderator
Reputation: 204 Joined: 25 Jan 2006 Posts: 8581 Location: 127.0.0.1
|
Posted: Wed Dec 15, 2010 12:47 pm Post subject: |
|
|
Here's a faster method using caching:
Code: |
#include <Windows.h>
#include <bitset>
int __cdecl main( int argc, TCHAR* argv[] )
{
std::bitset< 10000 > primeCache;
// Initialize the bitset to true.
primeCache.reset( );
primeCache.flip( );
// Initialize pos 0, 1 to false.
primeCache.set( 0, false );
primeCache.set( 1, false );
// Initialize rest of cache.
for( int x = 0; x * x < static_cast< int >( primeCache.size() ); x++ )
{
if( primeCache.test( x ) )
{
for( int y = x * x; y < static_cast< int >( primeCache.size() ); y += x )
primeCache.set( y, false );
}
}
/**
* Output of prime numbers.
*
*/
#define START_NUM 1
#define FINISH_NUM 1000
// Safety checks etc.
if( FINISH_NUM <= START_NUM )
return 0;
if( FINISH_NUM > primeCache.size() )
return 0;
// Print numbers.
for( int z = START_NUM; z <= FINISH_NUM; z++ )
{
printf( "%d: %s\r\n", z, ( primeCache.test( z ) == true ) ? "true" : "false" );
}
return 0;
} |
I wrote this based off of:
http://stackoverflow.com/questions/1042902/most-elegant-way-to-generate-prime-numbers/1043247#1043247
Using a cached set of numbers will result in a much faster application. The only real delay is the print out. _________________ - Retired.
|
|