Java Reference
In-Depth Information
import static java.lang.Math.ceil;
import static java.lang.Math.sqrt;
import static java.lang.Math.min;
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.nio.channels.*;
import java.nio.*;
import java.util.*;
import java.io.IOException;
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
getPrimes(primes); // Calculate the
primes
Path file = createFilePath("Beginning Java Stuff",
"primes.bin");
writePrimesFile(primes, file); // Write the file
}
// Calculate enough primes to fill the array
private static long[] getPrimes(long[] primes) {
primes[0] = 2L; // Seed the first
prime
primes[1] = 3L; // 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 = 5L;
outer:
for (; count < primes.length ; number += 2) {
// The maximum divisor we need to try is square root of number
Search WWH ::




Custom Search