Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I started programing Java about a week ago, and this is my first post here.

I came up with this method for determining if a number is prime. It has been working flawlessly except for the case of 1 or 0. I want to exclude 1 and 0 from being considered prime. However it doesn't seem to have any effect.

Java
//determines if number in form 'long' is prime. Returns boolean.
public static boolean isPrime(final long a){ 
		
	boolean is = true;
		
	for (double i = 2; i <= (.5*a); i++) {
			
		if ((a%i==0)||(a==0)||(a==1)){
			is = false;
		}//end if
	}//end for loop
		return is;
}//end of isPrime.
Posted
Comments
Sergey Alexandrovich Kryukov 10-Mar-14 22:13pm    
If you used the debugger, you would see the problem immediately. So, use the debugger, in case of any doubt of you runtime, any at all...
—SA
CarlPayne 10-Mar-14 22:56pm    
I tried the debugger and can quickly tell that it is over my head at the moment. I will do some research on it immediately.
I did get it to work by moving the comparison with 1 and 0 to an if statement before the loop.
And changed "i <= (.5*a)" to "i*i <= a"

But still, from a syntax standpoint, why didn't the || statements work as is?
Sergey Alexandrovich Kryukov 11-Mar-14 2:24am    
I told you what you have to do in my answer. Way too simple.
—SA

To start with, this is bad, redundant code. Why would you need to compare a with 0 and 1 in each iteration of your loop? Check it before loop and return immediately. Always use the debugger, in case of any doubt in your runtime, any at all.

—SA
 
Share this answer
 
Firstly don't use double, use modulo arithmetic to check.
Secondly, you need to loop until the square root.
Thirdly, what about negative numbers?
Finally, If you have special cases for 0, 1, 2 and 3 then your loop can be shorted if you read this[^]

Luckily I'm bored today. The method is STATIC because it does not use any member variables. The special cases shorten the run time considerably for any reasonably large number; say greater than 437;
Java
static boolean isPrime(long number)
{
	if (number < 0)
	{
		// negatives are prime based on the absolute value
		return isPrime(-number);
	}
	if (number == 0 || number == 1)
	{
		// first two cases, these are not PRIME
		return false;
	}
	if (number % 2 == 0 || number % 3 == 0)
	{
		// we just have the simple prime:
		return true;
	}
	for (long divisor = 5;
			divisor <= number/divisor;
			divisor = divisor + 6)
	{
		if ((number % divisor) == 0 || (number % (divisor  + 2)) == 0 )
		{
			// exit the loop, we're done:
			return false;
		}
	}
	return true;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900