Interview Question

Software Engineer Interview

given an integer, write code to list all primes preceding

  it.
Answer

Interview Answer

3 Answers

1

void printPrime(int n) {
    bool not_prime = false;

    for (int i=2; i<n; i++) {
        not_prime = false;
        for (int j=2; j<i; j++) {
            if (i%j==0 && i!=j) {
                not_prime = true;
                break;
            }
        }
        if(!not_prime)
            printf("%d\n", i);
    }
}

googler on Jul 29, 2014
0

This solution can be optimized further. No need to check for even numbers (except 2, 2 is the only prime even number). You can find if 'n' is prime when it is not divisible by any number between 2 to n/2. More optimizaton can be achieved if the range is reduced further from 2 to sqrt(n). But finding a sqrt will be tedious and might require inclusion of math.h library.

Toseef on Aug 2, 2014
0

there is a much more optimal solution, think about what you already know ;-) of course if this was an interview this would be my answer too (unless they asked for more performance.)

unemployed on Sep 28, 2014

Add Answers or Comments

To comment on this Question, Sign In with Facebook or Sign Up