Quick and easy prime number test because...

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
User avatar
MadPumpkin
Chaos Rift Maniac
Chaos Rift Maniac
Posts: 484
Joined: Fri Feb 13, 2009 4:48 pm
Current Project: Octopia
Favorite Gaming Platforms: PS1-3, Genesis, Dreamcast, SNES, PC
Programming Language of Choice: C/++,Java,Py,LUA,XML
Location: C:\\United States of America\Utah\West Valley City\Neighborhood\House\Computer Desk

Quick and easy prime number test because...

Post by MadPumpkin »

This is a quick and easy prime number test because I'm seriously sick of searching all over the web for a faster way. So I wrote three and decided that the one with the least lines of code actually looks like it works better.

Code: Select all

bool isPrime(long n)
{
	if (n < 2) return false;
	if (n < 4) return true;
	if (n % 2 == 0) return false; // if number modulo 2 returns 0 then it's even, and not prime
	const unsigned int i = sqrt((double)n) + 1;
	for (unsigned int j = 3; j <= i; j += 2)
	{
		if (n % j == 0)
			return false;
	}
	return true;
}
Oh and you must #include <math.h>
For more information look up Sieve of Eratosthenes and AKS. The codes based on both.
While Jesus equipped with angels, the Devil's equipped with cops
For God so loved the world that he blessed the thugs with rock
Image
Image
Image
User avatar
bnpph
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 75
Joined: Thu Mar 10, 2011 12:30 pm

Re: Quick and easy prime number test because...

Post by bnpph »

sqrt() is slow. Especially math.h's version.

There might be a builtin for finding next power of 2, but I forgot it.

Code: Select all

bool isPrime2(unsigned int n) {
  if (n % 2 == 0) return false;
  unsigned int nl = n;
  nl |= (nl >> 1);
  nl |= (nl >> 2);
  nl |= (nl >> 4);
  nl |= (nl >> 8);
  nl |= (nl >> 16);
  nl += 1;
  nl >>= ((__builtin_ctz(nl))>>1);
  for(unsigned int i = 3; i < nl; i += 2) {
    if(n % i == 0)
      return false;
  }
  return true;
}
Post Reply