find the smallest prime that is greater than 2*n

Given a number n I want to find a prime number which is the smallest prime that is greater than 2*n.I have done this but it gives correct answers for a few selected inputs only.

Code:

`public int prime(int num) {`

int k = 0;

int j;

for (int i = num; i <= 2 * num; i++) {

for (j = 2; j < i; j++) {

if (i % j == 0) {

break;

}

}

if (j == i)

k = i;

}

return k;

}

Re: find the smallest prime that is greater than 2*n

Your program doesn't match your description: if searches the numbers [num ... 2*num] and it finds the smallest prime number in that range.

kind regards,

Jos

Re: find the smallest prime that is greater than 2*n

You want to find the smallest prime that is greater than 2*n. In line 4 you search a number that is between the number itself and 2 * the number. For example if you pass number 5, line 4 runs as:

Code:

`for (int i = 5; i <= 10; i++) {`

After that, when it finally finds a prime, it doesn't break the initial for, thus continuing the search. Each new prime it founds, it overwrites the previous one. So the result is the highest prime between the number itself and 2 * the number.

Sutured