Interview Question

Software Engineer Interview

given an integer, write code to list all primes preceding


Interview Answer

3 Answers


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;
            printf("%d\n", i);

googler on Jul 29, 2014

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

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