Prime04
Home ] Up ]

 

// file:   prime04.cpp
// date:   09/04/2002
// author: AOUS

// assignment#1
// date assigned: 9/4/2002
// date due     : 9/11/2002


#include <iostream.h>
#include <math.h>


bool isPrime1(int m);
void testPrime1(void);
bool isPrime2(int m);
void testPrime2(void);
bool isPrime3(int m);
void testPrime3(void);


void main(void)
  {
  testPrime1();
  //testPrime2();
  //testPrime3();
  }


/*
Name:
  isPrime1

Description:
  A function to check if a given number
  is a prime number.  The function takes an 
  integer and returns true or false.  The name
  of the function is isPrime1().
  http://www.mathforum.org/dr.math/faq/faq.prime.num.html

Examples:
  2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31

Precondition:
  The number supplied should be >= 1

Postcondition:
  None

Algorithms:
  Algorithm1:
    if n is 1 return false
    if n is 2 return true
    if n is divisible by i=2 to n-1 then 
        return false
      else
        return true
    end algorithm


  Algorithm2:
    if n is 1 return false
    if n is 2 return true

    for i=2 to n-1 do
      if n%i == 0 then
        return false
      end for

    return true
    end algorithm

Class member/friend of:
  none
Prototype:
  bool isPrime1(int n)

Returns:
  true or false

Parameters and their descriptions:
  n hold the number to be tested

Shared external names and thheir descriptions:
  sqrt

Shared member names and thheir descriptions:
  none

Local variables and their descriptions:
  i
Source code:
*/
bool isPrime1(int n)
  {
  if (1 == n) return false;
  if (2 == n) return true;

  for (int i=2; i<=n-1; i++)
    if (n%i == 0) 
      return false;

  return true;
  }


void testPrime1(void)
  {
  cout << "testPrime1 *************\n";

  for (int m=1; m<1000; m++)
    {
    cout << m << " is" << ' ';
    if (isPrime1(m)) 
        cout << "Prime\n"; 
      else 
        cout << "composite\n";
    }
  }


bool isPrime2(int n)
  {
  if (1 == n) return false;
  if (2 == n) return true;

  for (int i=2; i<=n/2; i++)
    if (n%i == 0) 
      return false;

  return true;
  }


void testPrime2(void)
  {
  for (int m=1; m<10; m++)
    {
    cout << m << " is" << ' ';
    if (isPrime2(m)) 
        cout << "Prime\n"; 
      else 
        cout << "composite\n";
    }
  }


bool isPrime3(int n)
  {
  if (1 == n) return false;
  if (2 == n) return true;

  for (int i=2; i<=sqrt(n); i++)
    if (n%i == 0) 
      return false;

  return true;
  }


void testPrime3(void)
  {
  for (int m=1; m<10; m++)
    {
    cout << m << " is" << ' ';
    if (isPrime3(m)) 
        cout << "Prime\n"; 
      else 
        cout << "composite\n";
    }
  }