Calculate Prime Numbers
From Java Example Source Code
Contents |
[edit] Overview - Calculate Prime Numbers
This Java example program shows how to calculate prime numbers.
[edit] Java Source Code
- Package: com.darwinsys
- File: Primes.java
package com.darwinsys;
/** Compute prime numbers, after Knuth, Vol 1, Sec 1.3.2, Alg. "P". Unlike Knuth, I don't build table* formatting into computational programs; output is one per line. <p> Note that there may be more* efficient algorithms for finding primes. Consult a good book on numerical algorithms.** @author Ian Darwin*/public class Primes {
/** The default stopping point for primes */public static final long DEFAULT_STOP = 600L; //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 neededlong[] 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]);
}}
[edit] What Result You Can Get
Run this example, you will get:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599
[edit] Required External Libraries and/or Files for this Java Example
Need nothing.
[edit] How to Run this Java Example Program
We recommend running this Java example program with Eclipse.
For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.
It's fairly easy.
[edit] Question & Answer
Any question?
Click edit and post your question or answer here.
