1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
// checkFile.h
// Cedar Wiseman
// COSC 2030, Section 11, Spring 2014
// Project01
// January 29, 2014
// reads in pairs of integers, loops on range of integers calculating number of primes and integer with greatest number of divisors
// excessive commenting is for my future reference
#ifndef CHECK_H_
#define CHECK_H_
#include <iostream>
#include <fstream> //used by doCalculation
#include "math.h" // used by isPrime
using namespace std;
bool isPrime ( int num ) // doCalculation calls this, sending it a number for each interation of the for loop that goes from the
{ // first integer in the pair to the second
if ( num <= 1 )
{
return false; // 1 isn't prime
}
else if ( num == 2 )
{
return true; // 2 is prime
}
else if ( num % 2 == 0 )
{
return false; // if divisible by 2, it's not a prime
}
else
{
bool prime = true; // innocent until proven guilty
int divisor = 3; // after checking 1 and 2, 3 is the next potential divisor
double num_d = static_cast<double>( num ); // converts the passed integer into a double
int upperLimit = static_cast<int>( sqrt(num_d) + 1 ); // if the divisor is greater than the square root of the number, the
// number is prime (converted back to integer because of future integer
while ( divisor <= upperLimit ) // arithmetic)
{
if ( num % divisor == 0 )
{
prime = false; // means it's divisible by something
}
divisor += 2; // only need to check if potential divisors are odd
}
return prime;
}
}
void doCalculation ( istream & infile )
{
while ( true )
{
int a, b, c = 0, primecount = 0, most_divisors = 0;
if ( infile.fail() ) // check for end of file before every read
{
break;
}
infile >> a >> b; // taking in both integers in the pair
for ( int i = a; i <= b; i++ ) // it's assumed that a<b
{
int divisors = 0; // defined here because it must reset before each iteration
if ( isPrime(i) ) // callins isPrime for current iteration
{
primecount++; // increments if true
}
if ( i > 1 ) // this if else statement is necessary for situations where one of the integers is <2 because j=2
{ // in the following loop
for ( int j = 2; j <= i; j++ )
{
if ( i % j == 0 )
{
divisors++; // remainder of 0 means it's a divisor
}
}
}
else
{
divisors = 0; // necessary to get the correct output for cases such as the pair (1,1)
}
if ( divisors >= most_divisors ) // this is used for output of the most divisors
{
most_divisors = divisors;
c = i; // stores which integer has the most divisors
}
}
cout << endl << "Integer pair: " << a << " and " << b << endl << "Number of primes: " << primecount << endl << c
<< " has " << most_divisors + 1 << " divisor(s)" << endl;
}
}
#endif
|