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

• June 29th, 2012, 09:21 AM
mjr
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:

Code :

```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.
• June 29th, 2012, 11:52 AM
stdunbar
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.
• June 29th, 2012, 07:59 PM
Sean4u
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.