Java Reference
In-Depth Information
Here, if we don't find a command-line argument that we can convert to an integer, we just use a default
count of 100.
We can now generate the primes with code similar to that in Chapter 4 as follows:
long[] primes = new long[primesRequired]; // Array to store primes
primes[0] = 2; // Seed the first prime
primes[1] = 3; // and the second
// Count of primes found - up to now, which is also the array index
int count = 2;
// Next integer to be tested
long number = 5;
outer:
for (; count < 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 < count && primes[i] <= limit; i++)
if (number % primes[i] == 0) // Is it an exact divisor?
continue outer; // yes, try the next number
primes[count++] = number; // We got one!
}
Now all we need to do is add the code to write the primes to the file. Let's put this into a working example.
Try It Out - Writing Primes to a File
Here's the complete example with the additional code to write the file shown shaded:
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
public class PrimesToFile {
public static void main(String[] args) {
int primesRequired = 100; // Default count
if (args.length > 0) {
try {
primesRequired = Integer.valueOf(args[0]).intValue();
} catch (NumberFormatException e) {
System.out.println("Prime count value invalid. Using default of "
+ primesRequired);
}
}
long[] primes = new long[primesRequired]; // Array to store primes
primes[0] = 2; // Seed the first prime
primes[1] = 3; // and the second
Search WWH ::




Custom Search