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

1. Member Join Date
Mar 2014
Posts
8
Rep Power
0

## 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.

Java 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;
}```  Reply With Quote

2. ## 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  Reply With Quote

3. Member Join Date
Mar 2012
Posts
31
Rep Power
0

## 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:

Java 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  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•