I tried to write the BiggerThanPrime program which allows the user to give an input p and the program can find the next closest prime(n) to it such that the value of (n-p) is minimum.
Here is my code:
static boolean Prime (int n){
boolean NotPrime = true;
boolean result = true;
for (int i=2; i< n; i++){
NotPrime = (n % i != 0);
result = (result && NotPrime);
}
return result;
}
//Using Betrand's Postulate which states that there always exists at least one prime p s.t.a< p <2a
public static void main(String[] args) {
int p = Integer.parseInt(args[0]);
int k = p+1;
while( k > p && k< 2*p){
if( Prime(k) == true){
System.out.println("the next bigger prime than "+ p + " is "+ k);
} else{
k++;
}
}
}
But the while loop goes into infinite loop.
Thus the result is :
the next bigger prime than 20 is 23
the next bigger prime than 20 is 23
.
.
.
(infinitely goes on) :(
What am I doing wrong?