skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Tuesday, January 17, 2012

Program to Calculate Prime Numbers using Vector

Posted by Admin at 4:56 AM – 0 comments
 
Implement a version of the program to calculate prime numbers to use a Vector<> object instead of an array to store the primes.

import java.util.Vector;

public class MorePrimes {
  public static void main(String[] args) {
    Vector<Long> primes = new Vector<Long>();                          // Vector to store primes
    int primesRequired = 20;                                           // Number of primes required

    primes.add(new Long(2L));                                          // Seed the first prime
    primes.add(new Long(3L));                                          // and the second
    long number = 5L;                                                  // Next integer to be tested
    long divisor = 0L;                                                 // Stores current trial divisor

    outer:
    for( ; primes.size() < primesRequired; number += 2) {
      // The maximum divisor we need to try is square root of number
      long limit = (long)Math.ceil(Math.sqrt((double)number));

      // Divide by all the primes we have up to limit
      for(int i = 1; i < primes.size() && (divisor = primes.elementAt(i)) <= limit; ++i) {
        if(number%divisor == 0) {                                      // Is it an exact divisor?
          continue outer;                                              // Yes, try the next number
        }
      }
      primes.add(number);                                              // We got one!
    }
    // Output all the primes six to a line
    int count = 0;
    for(Long prime : primes) {
      System.out.printf("%15d", prime);
      if(++count%6 == 0) {
        System.out.println();
      }
    }
  }
}


Output of Above Java Program
              2              3              5              7             11             13
             17             19             23             29             31             37
             41             43             47             53             59             61
             67             71
Labels: Java Vector Example , Prime Number

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger