I made a program which can generate primes. I want the program to write to file. When I generate primes up to Integer.Max_Value it doesn’t write all of the primes for some reason and it just stops. Here’s my code:
import java.io.*;
public class Primes {
public static void main(String[] args) throws IOException {
generate(Integer.MAX_VALUE);
}
// generate primes.
public static void generate(int limit) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Primes.txt"));
writer.write(2);
for (int i = 3; i <= limit; i += 2) {
if (isPrime(i)) {
writer.write(Integer.toString(i));
writer.newLine();
}
}
writer.close();
}
// checking for primes
public static boolean isPrime(int n) {
for (int i = 2; i <= (Math.sqrt(n)); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
I think your program isn’t hanging at all, it’s just taking a long time to do its work.
As the numbers get larger, the amount of time taken to check them increases in proportion to their square root. Additionally, the distances between prime numbers is greater, the larger the numbers. Putting these together, the speed at which primes are found will tail off quite quickly.
Have you attached a debugger to your program, and paused execution to inspect the local variables and see where it’s got to? Have you even put in
System.out.println("About to calculate for " + i);? How do your know your program “just stops”?The first step should be some investigation into what your program’s actually doing. If you output timestamps with the println messages, you can also get an idea of how the speed of checking each individual number decays, and thus when you spot a pause you can have a rough estimate of how long the current check should take.
Besides, your program will never terminate, since you have an infinite outer loop. Your
forloop’s terminating condition isi <= Integer.MAX_VALUE, which means it will run until it finds anisuch thati > Integer.MAX_VALUE. Can you name a value foriwhere that will hold true?