Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JOptionPane;
- import javax.swing.UIManager;
- public class PrimerNumber {
- private static final long[] primes = new long[61521918];//new long[(int) (Runtime.getRuntime().maxMemory()/11)];
- static {
- System.out.println(primes.length);
- primes[0] = 2;
- primes[1] = 3;
- primes[2] = 5;
- //these are known and needed in the beginning
- }
- private static int idx = 3; //already assigned 3 primes
- public static void main(String[] args){
- Runtime.getRuntime().addShutdownHook(new Thread(){ //to be run when program exits
- public void run(){
- System.out.print("\nCalculated " + idx + " primes\n" + idx + "th prime: " + primes[idx - 1]);
- }
- });
- try {
- UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); //set UI to Windows/Mac/Linux (whatever native UI is)
- } catch (Exception useless){}
- final JFrame frame = new JFrame();//frame for gui
- frame.setUndecorated(true);//no buttons in pane
- final JButton button = new JButton("Exit");
- button.addActionListener(new ActionListener(){//when Exit button clicked
- public void actionPerformed(ActionEvent e) {
- frame.setVisible(false);
- frame.dispose();
- JOptionPane.showMessageDialog(null, "\nCalculated " + idx + " primes\n" + idx + "th prime: " + primes[idx - 1]);
- System.exit(0);
- }
- });
- frame.add(button);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setSize(500, 500);
- frame.pack();
- frame.setLocationRelativeTo(null);//center frame
- frame.setVisible(true);
- while(frame.isVisible()){
- System.out.println(calculateNextPrime());
- }
- }
- private static long calculateNextPrime(){
- if(idx == primes.length){
- System.out.println("\nCannot calculate more prime numbers (reached max memory usage).");
- System.out.print("Last prime calculated: ");
- System.exit(0);
- return primes[idx - 1];
- }
- primeSearch:
- for(long i = primes[idx - 1] + 2;; i += 2){ //use last prime as a starting point, but add 2 so it stays odd
- for(int j = 0; j < idx; j++){
- if(i % primes[j] == 0){ //check if any of the previous primes are a factor of current number
- //if no previous primes are a factor, then current number is a prime
- continue primeSearch;
- }
- }
- //if execution reaches here, no previous are a factor, so set the next prime number and increase index
- return primes[idx++] = i;
- }
- }
- }
Add Comment
Please, Sign In to add comment