Project Planning Question:

Download Job Interview Questions and Answers PDF

Write a function that counts the number of primes in the range [1-N]. Write the test cases for this function?

Project Planning Interview Question
Project Planning Interview Question

Answer:

This is what I came up with (C#):

PSEUDO:
-Craete a list of numbers uptill n number - n being int
parameter
-Pass this list into a function to check for primilaty for
the number and then print primes wile we count for primes

BACKGROUND OF THIS SOLUTION:

THEORY:
- we know primes are the numbers starting from 2 are
divisible with 1 and themselves only i.e. n being a prime
number can only be divisble as n/n or n/1. testing from a
prime is called "primilatiy test" for a number...
-the simplest primality test is to see if given a number n
is divisible by an integer m from 2 to n-1. If n is
divisible by n then n is a composite number otherwise its a
prime...

TO SPEED UP THE COMPUTING WE CAN ALSO:
Rather than testing till n-1 we can test the number till
Square Root of n i.e. if n is a prime number it can always
be factored into 2 values.

REFERENCE:
See here if you want to be a mathematician ;-).
http://en.wikipedia.org/wiki/Primality_test

THE CODE:

I would assume you know how to deal with lists in c# so I
will not get into that. Just create an integer based items
list "list<int>" etc. in C# which adds digits to the list
till number n. HINT: use a for loop ...LOL!!

public void CountPrimes(list<int> c)
{
list<int> primes = c.FindAll(
delegate(int a)
for (int i = 2; i <= Math.Sqrt(a); i++)
{
if (a % i == 0)
return false; //is not a prime
return true;//is a prime
}
//list primes in a list box and get the total count
label1.Text = "Total Primes = " + Convert.ToString
(p.count);
for (int count = 2; count < p.count; count++)
{
listbox.Items.Add(Convert.ToString(p[i]));
}
}

Download Project Planning Interview Questions And Answers PDF

Previous QuestionNext Question
Write the InStr function. Write the test cases for this function?How would you deal with changes being made a week or so before the ship date?