USInternetworking Interview Question
Software Engineer / Developersint sum_prime(int n) {
if (n <= 1)
return -1;
bool * euclid;
euclid = new bool[n-1];
for (int i = 0; i < n-1; i++) {
euclid[i] = false;
}
euclid[0] = true;
for (int i = 1; i < n-1; i++) {
if (!euclid[i]) {
int j = 2*(i+1) - 1;
while (j < n-1) {
euclid[j] = true;
j += i+1;
}
}
}
int sum = 0;
for (int i = 0; i < n-1; i++) {
if (!euclid[i])
sum += i+1;
}
return sum;
}
I agree with Smita. The whole pointe of the interview is not just coming out with the code. The interviewer will see first about your approach and then your implementation. I think it would be really nice to explain your logic in few sentences like a psuedocode and then write your own implementation would be helpful...
Sorry, I was trying to remember the algo from my head, and I made a couple mistakes in it. Calling it Euclid instead of Sieve for instance. Plus I iterate through the whole array while I only need to go until 1/2 way. And the arithmetic for the indices could be cleaner.
- Anonymous November 21, 2008The idea behind the "Sieve" is to "cross out" each non prime up until N. The way we do this, is that each time we come across a non crossed out number, we know it is prime, and thus all multiples of this number are NOT primes, so we cross them out. By the time we reach N we will have crossed out all non prime numbers and can sum up the remaining primes. Look up the Sieve of Erathosones or something like that for a cleaner solution!