Interview Preparation mode beta
Funny Facebook Status Funny Facebook Status
Enter your email address

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

Nice?Vote!

1 Answer

Nice?Vote!
public int CountPrimes(int n)
{
        List<int> primes = new List<int>();
        primes.Add(2);
 
        int i = 1;

        while (i < n)
        {
                int pivot = 0;
                bool isPrime = true;

                while (pivot < primes.Count)
                {
                      if (i % primes[pivot] == 0)
                      {
                            isPrime = false;
                            break;
                      }
                }
                if (isPrime)
                      primes.Add(i);
        }
        return primes.Count + 1; // The number 1 is also a prime and is not into array
}
answered 3 weeks ago by anonymous

Related questions