/** Mock Lab Test for 18th September 2008***/ /*Write a JAVA program to find the difference between the nth prime number and (n + k)th prime number for a given pair of a positive integers n and k. For example, if the input value of n = 2 and k = 3, then the output should be 8 because the 2nd prime number is 3 and 5th prime number is 11. Note: The input n and k must be taken from command line in this order.*/ /*keyidea: start from 2 and keep on finding prime numbers till we reach up to n+k th prime number. *in between store the nth prime number and print the difference in the end*/ class DiffPrime { public static boolean isprime(int num) { int i = 1; int sqroot = (int)Math.sqrt(num); if(num==2) { return true; } if(num % 2 == 0) { return false; } else { for( i = 3; i <= sqroot; i+=2) { if (num % i == 0) { return false; } } return true; } } public static void main(String args[]) { int n = Integer.parseInt(args[0]); int k = Integer.parseInt(args[1]); int count=0; int firstprime=0, nextprime=0; int i= 2; while(true) { if(isprime(i)) { count += 1; if(count == n) { firstprime = i; } if(count == (n + k)) { nextprime = i; System.out.println("the firstprime is" + firstprime + "the second prime is" + nextprime); System.out.println("difference is " + (nextprime - firstprime)); break; } } i += 1; } } }