WARNING. You will have a tendency to try to write your functions without writing contracts first. This is very bad practice, and will cause you to spend more time writing your programs than if you write the contracts first. The contracts serve as guides to your work, and are critical aspects of the programming process. If you skip over them, you can count on difficulties.
///////////////////////////////////////// // min // ///////////////////////////////////////// // min(x,y) returns the smaller of x // // and y. // ///////////////////////////////////////// int min(int x, int y) { if(x < y) return x; else return y; }
///////////////////////////////////////////// // prime // ///////////////////////////////////////////// // prime(n) returns 1 if n is prime, and // // 0 if n is not prime. // ///////////////////////////////////////////// bool prime(int n) { if(n <= 1) return 0; else { int k = 2; while(k < n) { if(n % k == 0) return 0; k++; } return 1; } }
/////////////////////////////////////////////// // nextPrime // /////////////////////////////////////////////// // nextPrime(n) returns the smallest prime // // number that is greater than n. // /////////////////////////////////////////////// int nextPrime(int n) { int k = n+1; while(prime(k) == 0) k++; return k; }
/////////////////////////////////////////////// // PrintPrimes // /////////////////////////////////////////////// // PrintPrimes(n) prints the first n prime // // numbers, one per line. // /////////////////////////////////////////////// void PrintPrimes(int n) { int k,i; k = 2; i = 0; while(i < n) { cout << k << endl; i++; k = nextPrime(k); } }
/////////////////////////////////////////////// // main // /////////////////////////////////////////////// // Read a number n and print the first n // // primes. // /////////////////////////////////////////////// int main() { int n; cout << "How many primes shall I print? "; cin >> n; cout << "The first " << n << " prime numbers are:\n"; PrintPrimes(n); return 0; }