Top

Optimized prime num method


C++ Code
+ 0 likes
Please Register to submit score.
Bookmark and Share
Average Score  0.0 (of 0 scores)
Date Added  Nov 01, 2009
Last Updated  Nov 14, 2009
Tags  number  prime 

Introduction

used to tell if a number is prime

you should find it a bit faster than your normal prime number algorithm

i'm not sure which compilers don't accept inline assembly, but i compiled in visual studio.

Grab the Code

#include <cmath>
 
bool prime(unsigned n)
{
	switch (n)
	{
		case 0:
		case 1:
			return false;
		case 2:
		case 3:
			return true;
		default:
			break;
	}
 
	double dSq = sqrt((double)n);
	unsigned sqrt = (int)dSq;
 
	unsigned prime;
	// check 2 to sqrt for divisibility
	__asm
	{
		mov esi, n    
		mov edi, sqrt
 
		mov ebx, 1  
		mov ecx, 1   
		_loop:
		inc ecx       
		cmp ecx, edi   
		ja _end       
		mov eax, esi
		xor edx, edx
		div ecx
		cmp edx, 0 
		jne _loop
		mov ebx, 0
 
		_end:
		mov prime, ebx
	}
	return (prime == 1);
}

Comments

  (0)  RSS

Commenting Options

Register or Login to Hawkee.com or use your Facebook or Twitter account by clicking the corresponding button below.

  
Bottom