Results 1 to 3 of 3
  1. #1
    tnahsin is offline Member
    Join Date
    Mar 2014
    Posts
    8
    Rep Power
    0

    Default 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;
    }

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,729
    Blog Entries
    7
    Rep Power
    21

    Default 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
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    Sutured is offline Member
    Join Date
    Mar 2012
    Posts
    30
    Rep Power
    0

    Default 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

Similar Threads

  1. Replies: 10
    Last Post: 05-17-2013, 02:20 PM
  2. Find a prime number
    By bam207 in forum New To Java
    Replies: 2
    Last Post: 11-16-2012, 07:42 PM
  3. Find the Biggest Number + Smallest
    By d4v1dz in forum New To Java
    Replies: 19
    Last Post: 10-26-2011, 07:43 AM
  4. find a prime number
    By loja11 in forum Threads and Synchronization
    Replies: 4
    Last Post: 02-17-2011, 09:54 AM
  5. Prime Number - System print all the prime numbers ...
    By pinkdreammsss in forum New To Java
    Replies: 20
    Last Post: 04-26-2009, 02:50 AM

Posting Permissions

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