GeeksforGeeks » Interview Questions
Google Interview Question for Software Engineer/Developer about Algorithms
(8 posts)-
Given a number, describe an algorithm to find the next number which is prime.
-
You're better off reading this:
http://www.technologywoman.com/2010/05/17/debunking-the-google-interview-myth/ -
#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; } -
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 !
-
@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; } -
@Shekhu
that was just a minute bug, thnx though for updating the post again :)
-
Why not use divide till n/2 only as after that it will never be needed.
-
rather than going to n/2, sqr_root(n) will be sufficient.
Reply
You must log in to post.