Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 04-12-2008, 09:39 PM
Java Tip's Avatar
Moderator
 
Join Date: Nov 2007
Posts: 1,691
Rep Power: 5
Java Tip will become famous soon enoughJava Tip will become famous soon enough
Default Computing prime numbers in Java
This Java program shows a simple method of computing prime numbers with Java.

Code:
public class Primes {
  /** The default stopping point for primes */
  public static final long DEFAULT_STOP = 4294967295L;
  /** The first prime number */
  public static final int FP = 2;

  static int MAX = 10000;

  public static void main(String[] args) {
    long[] prime = new long[MAX];

    long stop = DEFAULT_STOP;
    if (args.length == 1) {
      stop = Long.parseLong(args[0]);
    }

    prime[1] = FP;       // P1 (ignore prime[0])
    long n = FP+1;       // odd candidates
    int j = 1;        // numberFound

    boolean isPrime = true;  // for 3

    do {

      if (isPrime) {
        if (j == MAX-1) {
          // Grow array dynamically if needed
          long[] np = new long[MAX * 2];
          System.arraycopy(prime, 0, np, 0, MAX);
          MAX *= 2;
          prime = np;
        }
        prime[++j] = n;  // P2
        isPrime = false;
      }
      n += 2;        // P4

      for (int k = 2; k <= j && k < MAX; k++) {  // P5, P6, P8
        long q = n / prime[k];
        long r = n % prime[k];
        if (r == 0) {      
          break;
        }
        if (q <= prime[k]) {    // P7
          isPrime = true;
          break;
        }
      }
    } while (n < stop);        // P3

    for (int i=1; i<=j; i++)
      System.out.println(prime[i]);
  }
}
__________________
"The sole cause of man’s unhappiness is that he does not know how to stay quietly in his room." - Blaise Pascal
Bookmark Post in Technorati
Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Finding Largest Prime Factor perito New To Java 4 10-16-2008 07:10 AM
distributed computing in java pushpik Advanced Java 0 03-31-2008 07:50 PM
Prime numbers gapper New To Java 3 02-07-2008 11:09 AM
Computing Fibonacci numbers recursively Java Tip Java Tips 0 01-22-2008 09:20 PM


All times are GMT +2. The time now is 03:01 PM.



VBulletin, Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2009, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org