954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to make the prime number method more efficient?

I have a prime number method here which checks if the user input is a prime number, I've done some stuff to try to make it more efficient, but I am wondering if there is anything else that can be done, maybe even make the complexity class constant? Thanks. Below is my code.

public static boolean checkPrime (int n) {

		if (n!=2)
		{
			if (n%2==0)
			{
				return false;
			}
		}
		for (int i=3; i<=Math.sqrt(n);i+=2)
		{
			if (n%i==0)//if n divided by i has a remainder of 0, then not prime
			{
				return false; //number is not prime, return false for prime, terminate method
			}
		}

		return true; //number is prime, return true for prime, terminate method
	}
flyingcurry
Light Poster
44 posts since Apr 2010
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: