Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, April 5, 2010

The Sieve to detect Primes

Literally, Sieve is “A utensil for separating the finer and coarser parts of a pulverized or granulated substance from each other”. Eratosthenes, a Greek Mathematician, came up with such a sieve to filter out Prime numbers from a given set of integers. The process/algorithm came to be known as Sieve of Eratosthenes!
The Algo is pretty simple, start with number 2, cross all its multiples (till MAX_NUMBER), proceed with the next number 3 and cross all its multiples too and so on. The remaining numbers in the set will be primes. The algo itself brings in some optimizations!

1. All even numbers get cancelled in first iteration for 2. Next number (3) onwards, start directly checking for multiples starting with the square of the number.
2. The multiples need to be crossed for numbers < square root (MAX_NUMBER), because rest of the multiples would have got crossed earlier itself.

The code in Java for the Sieve of Eratosthenes is as follows:

 
public class SieveEratosthenes {
  private static final int MAX_NUMBER = 1000;
  public static void main(String[] args) {
    boolean[] arr = new boolean[MAX_NUMBER];
    int i, j;
    
    //Initialize the Boolean array to TRUE (i.e. Prime)
    for (i = 0; i < arr.length; i++)
      arr[i] = Boolean.TRUE;
    
    //Finish with all divisors of 2 to optimize code for the remaining
    for (i = 2; 2 * i < MAX_NUMBER; i++)
      arr[2 * i] = Boolean.FALSE;
    
    //Only odd numbers need to be considered in both loops, since
    //   Odd * Even = Even 
    //And all evens are covered as multiples of 2
    for (i = 3; i < (Math.sqrt(MAX_NUMBER)); i += 2) {      
      for (j = i; j * i < MAX_NUMBER; j += 2)
        arr[j * i] = Boolean.FALSE;
    }
    System.out.println("The primes below " + MAX_NUMBER + " are : ");
    int count = 0;
    for (i = 2; i < arr.length; i++)
      if (arr[i]) {
        System.out.println(i);
        count++;        
      }
    System.out.println("The total no of primes till " + MAX_NUMBER +  " are : " + count);
  }
}


Sunday, March 28, 2010

Java Books

4 Books you should read if you adore Java!

1. JLS : Java Language Specification, the blue-print of Java. This book gives an in-depth understanding of Java architecture.
2. SCJP : Almost all concepts cleared, from programming point of view.
3. Effective Java and Java Puzzlers : These two are mind-boggling books. If you feel you are a Java-Guru, do give these a try and verify it out for yourself! :)

Please feel free to add-on and share any other master-pieces!

Java Puzzlers

Borrowed from Java Puzzlers. An awesome book BTW!!
Guess the output of the two programs below:

1.
public class SetTest {

    public static final String[] URLNAMES =  {
        "http://javapuzzlers.com",
        "http://apache2-snort.skybar.dreamhost.com",
        "http://www.google.com",
        "http://javapuzzlers.com",
        "http://findbugs.sourceforge.net",
        "http://cs.umd.edu"
    };

    public static void main(String[] args) throws MalformedURLException {
        Set favourites = new HashSet();

        for (String names : URLNAMES) {
            favourites.add(new URL(names));
        }
        System.out.println("Size is : " + favourites.size());
    }
}

2.
public class Elvis {

    public static final Elvis INSTANCE = new Elvis();
    private final int beltSize;
    private static final int CURRENT_YEAR =
            Calendar.getInstance().get(Calendar.YEAR);

    private Elvis() {
        beltSize = CURRENT_YEAR - 1930;
    }

    public int beltSize() {
        return beltSize;
    }

    public static void main(String[] args) {
        System.out.println("Elvis wears a size " +
                INSTANCE.beltSize() + " belt.");
    }
}

Output 1:
Prints 4, if connected to internet and 5 else!! :) Checks for host names and in turn IP addresses for the site names entered as URL objects. Apparently, first and second strings resolve to same IP address. (Haven't verified it though, trusting the author!). URL equal() and hashcode() methods are broken, so, instead use URI objects and URI.create() method to create objects!

Output 2:
-1930
Initializing sequence when an object is created. First, static fields get default values, so INSTANCE defaulted to null and CURRENT_YEAR defaulted to 0. Then static initializers get called, accordingly, new Elvis() gets executed and beltsize gets initialized to 0-1930 = -1930!!!! Hence, the output..