GeeksforGeeks » Interview Questions

Google Interview Question for Software Engineer/Developer about Algorithms

(8 posts)

Tags:

  1. ganesh
    guest
    Posted 2 years ago #

    Given a number, describe an algorithm to find the next number which is prime.

  2. James
    guest
    Posted 2 years ago #

  3. Shekhu
    Member
    Posted 2 years ago #

    #include<stdio.h>
    
    int nextPrime(int n)
    {
      int i;
      n = n + 1; 
    
      // If n is even then convert it to odd
      if(n%2 == 0)
        n = n + 1;
    
      // Loop until we get a prime number
      while(1)
      {
        for(i = 2; i < n; i++)
        {
           if(n%i == 0)
             break;
        }      
    
        // If nothing divides n then n is prime
        if(i == n)
          return n;
    
         // Else Look for the next odd no.
         n = n + 2;
      }
    }    
    
    int main()
    {
      printf("\n Next prime is %d", nextPrime(13));
      getchar();
      return 0;
    }
    
  4. Manan
    Member
    Posted 1 year ago #

    Here, if I pass 1 as a value i.e nextPrime(1), it should return 2( as it is the next prime number), but it actually returns 3. Correct me, if I am wrong !

  5. Shekhu
    Member
    Posted 1 year ago #

    @Manan,
    nice point :) I think it has to be handled separately.

    #include<stdio.h>
    
    int nextPrime(int n)
    {
      int i;
      n = n + 1; 
    
      if(n == 1)
        return 2;   
    
      // If n is even then convert it to odd
      if( n%2 == 0)
        n = n + 1;
    
      // Loop until we get a prime number
      while(1)
      {
        for(i = 2; i < n; i++)
        {
           if(n%i == 0)
             break;
        }      
    
        // If nothing divides n then n is prime
        if(i == n)
          return n;
    
         // Else Look for the next odd no.
         n = n + 2;
      }
    }    
    
    int main()
    {
      printf("\n Next prime is %d", nextPrime(13));
      getchar();
      return 0;
    }
    
  6. Manan
    guest
    Posted 1 year ago #

    @Shekhu

    that was just a minute bug, thnx though for updating the post again :)

  7. Amol
    guest
    Posted 6 months ago #

    Why not use divide till n/2 only as after that it will never be needed.

  8. ism
    guest
    Posted 6 months ago #

    rather than going to n/2, sqr_root(n) will be sufficient.


Reply

You must log in to post.

RSS feed for this topic