View Single Post
  #2 (permalink)  
Old January 19th, 2005, 01:33 PM
mehdi62b mehdi62b is offline
Friend of Wrox
 
Join Date: Jul 2004
Posts: 623
Thanks: 0
Thanked 1 Time in 1 Post
Default

for prime numbers there are two general ways,
n is a prime number if it has just two factors.(1 and that number)
for example,
2 is a prime number because its factors are{1,2}
3 is a prime number because its factors are{1,3}
23 is a prime number because its factors are{1,23}
6 is not a prime number because its factors are{1,2,3,6}
1 is not a prime number because its factor is{1}
every even number except 2 is not a prime number because its factors are more than 2(for example for 2n we have at least 1,2,n,2n as its factors}
and its code is,
Code:
//Not tested
bool IsPrime(int n)
{
  int counter=0;
  for(int i=1; i<=n ; i++)
   if (n%i==0) counter++;
  if (counter==2) return true;
  return fasle;
}

but another way is,
for every number like n,it is a prime number if there is no factor from 2 to its root(n^1/2) for example,
12 is not a prime because between ranges from 2 to 3(3<=12^1/2) 2 and 3 are the factors for 12,
and its code is,
Code:
//Not tested
bool IsPrime(int n)
{
  //I'm not sure what is the right function for sqrt
  int root=(int)sqrt(n);
  for(int i=2; i<=root ; i++)
   if (n%i==0) return fasle;
  return true;
}
probably the second way is faster and better,
(if you just want to generate the prime numbers between two number there is a smart solution called Eratostenes Sieve,check out its link).

_____________________________
Mehdi.
software engineering student.
Looking for a good job for summer 2005.
Reply With Quote