Java Reference
In-Depth Information
long limit = (long)ceil(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] == 0L) // Is it an exact
divisor?
continue outer; // yes, try the
next number
primes[count++] = number; // We got one!
}
return primes;
}
// Create the path for the named file in the specified directory
// in the user home directory
private static Path createFilePath(String directory, String
fileName) {
Path file = Paths.get(System.getProperty("user.home")).
resolve(directory).resolve(fileName);
try {
// Make sure we have the directory
Files.createDirectories(file.getParent());
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
System.out.println("New file is: " + file);
return file;
}
// Write the array contents to file
private static void writePrimesFile(long[] primes, Path file) {
final int BUFFERSIZE = 100; // Byte buffer size
try (WritableByteChannel channel = Files.newByteChannel(
file, EnumSet.of(WRITE,
CREATE))) {
ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
LongBuffer longBuf = buf.asLongBuffer();
// View buffer for
type long
int primesWritten = 0;
// Count of primes
written to file
while (primesWritten < primes.length) {
longBuf.put(primes,
// Array to be written
primesWritten,
// Index of 1st element
to write
min(longBuf.capacity(), primes.length -
primesWritten));
buf.limit(8*longBuf.position());
// Update byte buffer
position
channel.write(buf);
primesWritten += longBuf.position();
longBuf.clear();
buf.clear();
Search WWH ::




Custom Search