Monday, 30 September 2013

Program to print all the twin prime combinations b/w the given inputs

//java code

class PrintTwinPrimes{

public static void main(String[] args) {
int num1 = 0,num2 = 0;
int input1 = Integer.parseInt(args[0]);
int input2 = Integer.parseInt(args[1]);
for( int i = input1 ; i <= input2 ; i++)
{
if(isPrime(i))
{
num2 = num1;
num1 = i;
}
if( (num1 - num2) == 2 )
{
System.out.println(num1+"  "+num2);
num2 = 0;
}
}
}
static boolean isPrime(int num)
{
for(int i = 2 ; i <= num/2 ; i++ )
{
if( num % i == 0 )
{
return false;
}
}
return true;
}
}

// compile
javac PrintTwinPrimes.java
// run
java PrintTwinPrimes 2 1000

-- at the time of running the program need to give inputs, otherwise ArrayIndexOutOfBoundException will raise
or else you can validate the program instead

public static void main(String[] args) {
if(args.length != 2) {
System.out.println("Enter only two integer inputs");
return;
}
int num1 = 0,num2 = 0;
int input1 = Integer.parseInt(args[0]);
int input2 = Integer.parseInt(args[1]);
for( int i = input1 ; i <= input2 ; i++)
----------------
---------------

similarly if you want a robust program, you can validate that the first input should be smaller than second input

No comments:

Post a Comment