Sunday, May 7, 2017

#codingexercise
Count pairs with sum as prime number and less than n. The numbers in the pair are each greater than or equal to 1 and less than n and they are not equal to each other

Get all prime numbers less than n.


Prime numbers can be generated with the sieve of Eratosthenes

This is a very simple way to filter out the prime numbers upto n.
for i ranging from 2 to square root of n:
     for j ranging from multiples of i upto n
          mark the number as not prime
those that remain unmarked are the primes.    
            int count = 0;
            for (int i = 0; i < primes.Count; i++)
                for (int j = 0; j <= i; j++)
                    if (primes[i] != primes[j] && primes.Contains(primes[i] + primes[j]) && primes[i] + primes[j] < 30)
                    {
                        Console.WriteLine("{0},{1}", primes[j], primes[i]);
                        count++;
                    }
            Console.Write("Count={0}", count);      


No comments:

Post a Comment