Thursday, January 15, 2015

fastest ways to determine primary numbers in java

For some of programs and for some programming exercises, we need to  determine whether a number is a primary number or not. That is very simple right... even newbies to programming can come up with a solution with java.
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

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...