Saturday, October 20, 2012

Mathematics4

Q4. How to determine if a given number is prime?
Answer: 

public class Mathematics4 {
    public static boolean isPrime(int num) {
        // return false if num is 1
        if (num == 1) {
            return false;
        }

        // return false if num is greatrer than 2 and even
        if ((num > 2) && ((num & 1) == 0)) {
            return false;
        }

        int squareRootOfNum = (int) (Math.sqrt(num));
        for (int i = 2; i <= squareRootOfNum; i++) {
            if ((num % i) == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        for (int i = 1; i <= 11; i++) {
            System.out.println(i + " is prime: " + isPrime(i));
        }
    }
}

  
  • Orde of complexity for above algo: 
    • O(1) for even numbers 
    • O(sqrt(n)) if n is odd

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.