Function to find Prime Numbers

Hey guys, I was hoping someone could let me know if this is a good function to determine if the number in 'n' is a prime number. Here's why I have so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
bool isPrime (long n)
{
	long i = 0;
	
	if(n == 1)
		return false;
	else if (n == 2)
		return true;
	else if (n % 2 == 0)
		return false;
	else
		{
			//check to see if it is prime
			for (i = 3; i < n; i+=2)
			{
			if (n % i == 0)
				
				return false;
				
			else  if (i == n)
			return true;
			}
		
		}
		return 0;
}
In the loop, we need to check for divisibility only up to (and including) the square root of n.

All prime numbers greater than 3 can be written as either 6*m - 1 or 6*m + 1 where m = 1, 2, 3, ....
So the trial divisions are required only if the remainder when divided by 6 is either 1 or 5.

you can reduce the time complexity of your algorithm. There are ways to do so, you can search the wikis.

In your code for instance iteration till n/2 shall serve the purpose instead of n.
also I would not include the following check:
else if (i == n)
return true;
the statement unnecessarily make checks at each iteration. I would simply return true whenever the program comes out of the "for" loop.
Topic archived. No new replies allowed.