/*
 * File: PerfectNumbers.cpp
 * ------------------------
 * This program tests the isPerfect function by generating all the
 * perfect numbers up to some user-specified upper bound.
 */

#include <iostream>
#include "console.h"
#include "simpio.h"
using namespace std;

/* Function prototypes */

void getLimits(int & lower, int & upper);
void findPerfectNumbers(int lower, int upper);
bool isPerfect(int n);
int sumOfProperDivisors(int n);

/* Main program */

int main() {
   int lower, upper;
   getLimits(lower, upper);
   findPerfectNumbers(lower, upper);
   return 0;
}

/*
 * Function: getLimits
 * Usage: getLimits(lower, upper);
 * -------------------------------
 * Reads in the two limits for the search from the user.
 */

void getLimits(int & lower, int & upper) {
   lower = getInteger("Enter lower limit: ");
   upper = getInteger("Enter upper limit: ");
}

/*
 * Function: findPerfectNumbers
 * Usage: findPerfectNumbers(lower, upper);
 * ----------------------------------------
 * Finds and prints all the perfect numbers between lower and upper,
 * inclusive.
 */

void findPerfectNumbers(int lower, int upper) {
   for (int i = lower; i <= upper; i++) {
      if (isPerfect(i)) {
         cout << i << endl;
      }
   }
}

/*
 * Function: isPerfect
 * Usage: if (isPerfect(n)) . . .
 * ------------------------------
 * This function returns true if n is a perfect number.  The
 * actual work is done by the sumOfProperDivisors function.
 * This function merely implements the definition of a perfect
 * number (see Euclid's Elements, book VII, definition 22).
 */

bool isPerfect(int n) {
   return (sumOfProperDivisors(n) == n);
}

/*
 * Function: sumOfProperDivisors
 * Usage: sum = sumOfProperDivisors(n);
 * ------------------------------------
 * This function returns the sum of the proper divisors of an
 * integer.  The implementation plan is to count through all
 * the possible factors, check each one, and add any divisors
 * to a running total.
 */

int sumOfProperDivisors(int n) {
   int sum = 0;
   for (int i = 1; i < n; i++) {
      if (n % i == 0) sum += i;
   }
   return sum;
}
