Microsoft Interview Question: Write a program to print out ... | Glassdoor

Interview Question

Program Manager Intern Interview Redmond, WA

Write a program to print out the first n primes.

Answer

Interview Answer

3 Answers

0

public static void printNPrimes(int n){
      if(n==0){
         return;
      }
      if(n>1){
         System.out.println(2);
         int x=3;
         while(n>0){
             if(x%Math.sqrt(x)!=0){
             System.out.println(x);
             }
             x=x+2;
             n--;
          }
      }
   }

Bharadwaj Tanikella on Mar 20, 2014
0

Fixed.

  public static void printNPrimes(int n){
      if(n==0){
         return;
      }
      if(n>=1){
         System.out.println(2);
         int x=3;
         while(n>1){
             if(x%Math.sqrt(x)!=0){
             System.out.println(x);
             }
             x=x+2;
             n--;
          }
      }
   }

Bharadwaj Tanikella on Mar 20, 2014
1

Can you explain your logic?
I tried your program in C++, and it even prints 21 and 27 as prime numbers.
This is my code, where fmod is a function that calculated the modulus result of 2 decimals (double).
int main(){
    int n;
    cin>>n;
      if(n==0){
         return 0;
      }
      if(n>=1){
         cout1){
             if(fmod(x,sqrt(x))!=0){
             cout<<x<<" ";
             }
             x=x+2;
             n--;
          }
      }
      return 0;
   }

Krishna Mittal on Jul 7, 2015

Add Answers or Comments

To comment on this, Sign In or Sign Up.