Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Wondering if there's a way to make this more efficient.

1. ## Wondering if there's a way to make this more efficient.

I have the following method for determining whether or not an integer value is a prime number:

```public boolean isPrime(int value){
if(value < 2)
return false;
else
{
int xSquareRoot = (int)Math.sqrt((double)value);

for (int x = 3; x <= xSquareRoot; x+=2)
if(value % x == 0)
return false;
}
return true;
}```

The for loop seems like it would be a waste of time and resources, and that it would be inefficient.

I'm just wondering if there's maybe a way I could make this more efficient. I mean, it works very quickly now, but it just seems like iterating over every odd number up to the integer square root of a number seems like a resource drain, especially for large primes, where the code would have to do several thousand iterations.

2. ## Re: Wondering if there's a way to make this more efficient.

Take a look at this link. Your algorithm falls under the "Naive methods" and can be improved.

Do they not have google where you're at? This took about 30 seconds to find.

3. ## Re: Wondering if there's a way to make this more efficient.

Remember if your function argument is int or smaller and your function return value is int or smaller, that there's *by definition* a static alternative on reasonably common hardware. Your "boolean isPrime(int)" for example could be implemented as a 128MB array. I'm not suggesting you add a 128MB object to your project, just responding to your question as-asked.

4. ## The Following User Says Thank You to Sean4u For This Useful Post:

cristian_ny95 (June 29th, 2012)