I want my program to test two BigInteger
s at the same time. As of now my code is testing one at a time. Since I want the code to be the same for both runs, is there a simple synchronized statement that I would be able to use to implement this?
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Enter number ");
int number = Integer.parseInt(input);
BigInteger num = new BigInteger(input);
String output = num + " is" + (IsPrime(num) ? " " : " not ")
+ "a prime number.";
JOptionPane.showMessageDialog(null, output);
}
public static boolean IsPrime(BigInteger num) {
if (num.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
return false;
for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(num) <= 0; i =
i.add(new BigInteger("2"))) {
if (num.mod(i).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
return true;
}
}
I have reached a solution to my question.
Because two integers were being tested I needed to create a textOne and a textTwo to test each individually for primeness.
public static boolean IsPrime(BigInteger textOne) {
// check if number is a multiple of 2
if (textOne.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
return false;
}// if not, then just check the odds
for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(textOne) <= 0; i =
i.add(new BigInteger("2"))) {
if (textOne.mod(i).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
return true;
}
public static boolean IsPrime2(BigInteger textTwo) {
// check if number is a multiple of 2
if (textTwo.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
return false;
}// if not, then just check the odds
for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(textTwo) <= 0; i =
i.add(new BigInteger("2"))) {
if (textTwo.mod(i).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
return true;
}
I designated that num and num2 be designated for the BigIntegers so that output would reflect the following..
public void run() {
String output = num + " is" + (IsPrime(num) ? " " : " not ")
+ "a prime number.";
lblResults.setText(output);
String output2 = num2 + " is" + (IsPrime(num2) ? " " : " not ")
+ "a prime number.";
lblResults2.setText(output2);
}}