Garg.mamta1828
BAN USERAssuming same function called multiple times
import java.util.Vector;
/*
* To get the nth prime number , say if n=0, return 2, n=1, return 3 and so on
*
* Here i am using the scenario where same function might be called multiple times during single execution
* Not handled Exception is range of int
*/
public class PrimeTester {
private static Vector<Integer> objVector = new Vector<Integer>();
public static int getnthPrime(int n)
{
if( n < 0 )
throw new IllegalArgumentException("Illegal Arument = " + n);
//Now check if the objVector has already the prime number. Consider the scenario when same call is made multiple times
if( objVector == null || objVector.size()==0)
{
objVector.add(2);
objVector.add(3);
}
int intVectorSize = objVector.size();
if ( intVectorSize > n )
return objVector.get(n);
//Keep on finding prime numbers till n is meet
//Find next prime
int item = objVector.get(intVectorSize-1);
while ( intVectorSize <= n )
{
item = item + 2;
if(isPrime(item))
{
objVector.add(item);
intVectorSize++;
}
}
return objVector.get(intVectorSize-1);
}
private static boolean isPrime(int item)
{
for (int i=0 ; i < objVector.size(); i++)
{
if( (item%(objVector.get(i))) == 0 )
return false;
}
return true;
}
}
Another optimization can be in isPrime. We need to iterate for loop till item /2 > objVector.get(i)
- Garg.mamta1828 June 30, 2013