/* * Aresh Saharkhiz * saharkiz@gmail.com * Associate Professor / Mapua Institute of Technology / Philippines */ using System; // Introduction to Software Testing // Authors: Paul Ammann & Jeff Offutt // Chapter 2, section 2.3, page 63 /// /// ***************************************************** /// Finds and prints n prime integers /// Jeff Offutt, Spring 2003 /// ********************************************************* /// internal class printPrimes_class { private static bool isDivisible(int i, int j) { if (j % i == 0) { return true; } else { return false; } } private static void printPrimes(int n) { int curPrime; // Value currently considered for primeness int numPrimes; // Number of primes found so far. bool isPrime; // Is curPrime prime? int[] primes = new int[100]; // The list of prime numbers. // Initialize 2 into the list of primes. primes[0] = 2; numPrimes = 1; curPrime = 2; while (numPrimes < n) { curPrime++; // next number to consider ... isPrime = true; for (int i = 0; i <= numPrimes - 1; i++) { // for each previous prime. if (isDivisible(primes[i], curPrime)) { // Found a divisor, curPrime is not prime. isPrime = false; break; // out of loop through primes. } } if (isPrime) { // save it! primes[numPrimes] = curPrime; numPrimes++; } } // End while // Print all the primes out. for (int i = 0; i <= numPrimes - 1; i++) { Console.WriteLine("Prime: " + primes[i]); } } // end printPrimes public static void Main(string[] argv) { // Driver method for printPrimes // Read an integer from standard input, call printPrimes() int integer = 0; if (argv.Length != 1) { Console.WriteLine("Usage: java printPrimes v1 "); return; } try { integer = Convert.ToInt32(argv[0]); } catch (FormatException) { Console.WriteLine("Entry must be a integer, using 1."); integer = 1; } printPrimes(integer); } }