Guest User

Untitled

a guest
Oct 22nd, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import javax.swing.*;
  2.  
  3. public class Goldbachs {
  4.  
  5.     // This method decides if number is prime or not and returns true or false.
  6.     public static boolean isPrime(int i) {
  7.         for (int u = 2; u < i; u++) {
  8.             if (i%u==0)
  9.                 return false;
  10.         }
  11.         return true;
  12.     }
  13.  
  14.     public static void main (String[] args) {
  15.  
  16.         while (true) { 
  17.             String s = JOptionPane.showInputDialog("Insert an even number greater "
  18.                 + "than 2 and I'll calculate \nwhich primes can be summed up"
  19.                     + " to form that number!", JOptionPane.QUESTION_MESSAGE);
  20.             if (s == null)
  21.                 break;
  22.            
  23.             int inputNumber = Integer.parseInt(s);
  24.             String result = "";
  25.             int numberofRows = 0;
  26.            
  27.             //Does inputNumber meet the requirements?
  28.             if (inputNumber>2 && inputNumber%2==0) {
  29.             //Which prime numbers are canditates to form inputNumber?
  30.                 for (int p = 1; p <=(inputNumber/2); p++) {
  31.                 //Is there another prime suitable to form inputNumber?
  32.                     if ((isPrime(p)) && (isPrime(inputNumber-p))) {
  33.                         result = result + p + " + " + (inputNumber-p) + "\n";
  34.                             numberofRows = numberofRows + 1;
  35.                         }
  36.                     }
  37.             if (numberofRows > 30) {
  38.                 System.out.println (result);
  39.             }
  40.             else {
  41.                 JOptionPane.showMessageDialog(null, result , "Here are your primes!",
  42.                     JOptionPane.INFORMATION_MESSAGE);
  43.             }
  44.             }
  45.                        
  46.             else {
  47.                 JOptionPane.showMessageDialog(null, "Invalid number, please pick a"
  48.                 + " new one.", "Number does not meet the requirements!", JOptionPane.ERROR_MESSAGE);
  49.             }
  50.         }
  51.     }
  52. }
Add Comment
Please, Sign In to add comment