Arsalan's Musings on Software

Software design and development techniques, ideas, and source code snippets…

Count prime numbers in a range (C# Solution)

with 2 comments

Problem: Given a range of integers, count the number of primes. Also list the prime numbers in the range.

using System;

namespace SolvingSmallProblems
{
public class Program
{
static void Main(string[] args)
{
int defaultLowNum = 1;
int defaultHighNum = 50;
int lowNum, highNum;
PrimeNumberPuzzles prime = new PrimeNumberPuzzles();

Console.WriteLine(“PRIME NUMBER COUNT PROGRAM”);
Console.WriteLine();
Console.WriteLine(“Please enter start number”);
try
{
lowNum =
Convert.ToInt32(Console.ReadLine());
}
catch (Exception)
{
lowNum = defaultLowNum;
}

Console.WriteLine(“Please enter end number”);
try
{
highNum = Convert.ToInt32(Console.ReadLine());
}
catch (Exception)
{
highNum = defaultHighNum;
}

if (lowNum < 1) { lowNum = defaultLowNum; } if (highNum < lowNum) { highNum = defaultHighNum; } int totalPrimes = prime.CountPrimes(lowNum, highNum); Console.WriteLine(); Console.WriteLine("Total number of prime numers between " + lowNum.ToString() + " and " + highNum.ToString() + " is " + totalPrimes + "."); Console.ReadKey(); } } public class PrimeNumberPuzzles { public int CountPrimes(int low, int high) { int count = 0; for (int num = low; num <= high; num++) { if (IsPrime(num)) { Console.Write(num + " "); count++; } } return count; } bool IsPrime(int num) { bool isNumPrime = true; if ( num == 2) { return true; } else if (num == 1) { return false; } else if (num < 1) { throw new Exception("Invalid number!"); } else { int remainder; for (int test = 2; test < num - 1; test++) { remainder = num % test; if (remainder == 0) { isNumPrime = false; } } return isNumPrime; } } } }[/sourcecode]

Written by Arsalan A.

January 21, 2008 at 6:10 pm

Posted in Code

2 Responses

Subscribe to comments with RSS.

  1. test < num – 1? Don’t you mean test < (num/2)? Your loop is doing much more work than it needs to.

    Marco Casalaina

    April 16, 2008 at 2:28 pm

  2. Marco: You are right. However, for a large n, n/2 and n-1 will both give O(n). Thanks for the comment.

    Arsalan

    April 16, 2008 at 3:01 pm


Leave a comment