Archived

This topic is now archived and is closed to further replies.

unknownnick

prime numbers

Recommended Posts

I don''t know if this has anything to do with games, but... I have an algorithm for searching prime numbers... the code would look like this
  
#include <windows.h>
#include <math.h>
#include <iostream>
using namespace std;

int n=0;
int x=3;

bool us_prime(int number) 
{ 
  int max_number = (int)(sqrt(number)+0.5); 
  int i = 3; 

  if (number % 2 == 0) 
   return false; 

  while (i<max_number) 
  { 
   if (number % i == 0) 
     return false; 
   i += 2; 
  } 
  return true; 
} 

int main(){
	
	cin >> n;

	for(x; x<n; x+=2){
		if(is_prime(x))
			cout << x << endl;
	}

	cin >> n;

	return 0;
}
  
I hope it''ll work. And now the question. Can anyone find me even faster way of searching them?

Share this post


Link to post
Share on other sites
Well... this technique isn''t anything new. The original algo doesn''t have that "0.5" in it though, as far as i remember.. cuz itz not necessary.

I saw some indian guys coming up with a faster technique few months back and the doc wos posted somewhere here in gamedev.... SEARCH SEARCH !

Share this post


Link to post
Share on other sites
Every prime is 6n+/-1 for some natural number n except for 2 and 3, but every 6n+/-1 is not prime. You can use that to further reduce the numbers you check. For instance it would eliminate 9, 15 and 21. So step by six starting at 5 and check two numbers per pass through the loop. That way you only check 1/3 of the numbers instead of 1/2 of them. You could also use 30n+/-7, 30n+/-11 and 30+/-13, but that gets a little cumbersome and only reduces it to 1/5 from 1/3.

Hum, I guess that is a bigger reduction than from 1/2 to 1/3, but it is still cumbersome.

[edited by - LilBudyWizer on November 3, 2002 7:44:51 PM]

Hehe, well, I guess you might want to include 30n+/-1 in there if you wanted it to be right which makes it 8/30=4/15 instead of 1/5 which means you only reduced it by 1/5 by using 30 versus 6.

[edited by - LilBudyWizer on November 3, 2002 7:56:21 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by browny
I saw some indian guys coming up with a faster technique few months back and the doc wos posted somewhere here in gamedev.... SEARCH SEARCH !


Actually, while the algorithm they discovered indeed runs in polynomial time, it is still slower than the algorithms developed today because it requires a very large-ordered polynomial.

Share this post


Link to post
Share on other sites