
Patrick B. answered 07/15/19
Math and computer tutor/teacher
Your function for checking the prime number has TWO problems...
your loop counter should start at 2, not 1 and end with a-1;
Actually , you do not need to check them all... you only need to go half way.
If you do not find a divisor by then, there aren't any.
But as written a%1 will ALWAYS be zero because anything divides by 1 evenly
Here is the revamped code.....
======================================
import java.io.*;
class TwinPrimes
{
private Console console;
private int num1, num2;
//constructor
TwinPrimes()
{
console = System.console();
num1 = num2 = 0;
}
// only need to go half way : if you don't find a divisor by then, there aren't any !!!
private boolean IsPrime ( int X)
{
int N = X/2;
boolean boolReturn=true; //assumes it is prime until proven otherwise;
for (int i=2; i<=N; i++)
{
if ((X % i)==0)
{
boolReturn=false;
}
}
return(boolReturn);
}
//returns 1 if the two numbers are twin primes, 0 if they are not twin primes, -1 on error
int Go()
{
String inbuff;
int iReturn = 0; //begins pessimisticly, assumes they are not twin primes until it is proven that they are
try
{
//perhaps you can trap for number format exception if the user inputs something funny
System.out.print(" Please input the first prime number :>");
inbuff = console.readLine();
num1 = Integer.parseInt(inbuff);
System.out.print(" Please input the second prime number :> ");
inbuff = console.readLine();
num2 = Integer.parseInt(inbuff);
//swaps them if out of order
if (num1 < num2)
{
int temp = num2;
num2 = num1;
num1 = temp;
} //swap
if (
(IsPrime(num1)) &&
(IsPrime(num2)) &&
((num1-num2)==2)
)
{
iReturn = 1;
} //if isPrime and they differ by 2
}//try
catch (Exception ex)
{
iReturn = -1;
System.out.println(" Input error has occured !!! ");
}
return(iReturn);
}
public static void main( String args[])
{
TwinPrimes myTwinPrimes = new TwinPrimes();
int iReturn = myTwinPrimes.Go();
switch (iReturn)
{
case 0:
{
System.out.println(" They are not twin primes !!!");
break;
}
case 1:
{
System.out.println(" They are twin primes !!! ");
break;
}
case -1:
{
System.out.println(" Input error has occured !!! ");
break;
}
} // switch
} //main
} //class TwinPrimes