But when we are working with large number of numbers,we need more efficient piece of code. Here is some efficient piece of codes found on programming question and answer sites.
public static boolean isPrime2(int n) { if (n <= 1) return false; if (n == 2) return true; if (n % 2 == 0) return false; for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) { if (n % i == 0) return false; } return true; }
still we can do some improvements to this code
boolean isPrime(long n) { if(n < 2) return false; if(n == 2 || n == 3) return true; if(n%2 == 0 || n%3 == 0) return false; long sqrtN = (long)Math.sqrt(n)+1; for(long i = 6L; i <= sqrtN; i += 6) { if(n%(i-1) == 0 || n%(i+1) == 0) return false; } return true; }
and some elegant answers are also there(this is much slower than others)...
public static boolean isPrime(int n) { return !new String(new char[n]).matches(".?|(..+?)\\1+");
But the tricks needed to achieve speed usually sacrifices elegancy.
So,there are lot of new,efficient,elegant algorithms to everywhere. find out, enjoy.. stay with LETS SEE to see more.. :)
No comments:
Post a Comment