I have to write a program by tonight and i am stuck on one particular part. My code has to have two numbers entered and then list the divisors of the first and second number. Then it has to tell how many divisors each number has( this is my problem). Than it has to tell if they have the same number of divisors or which one has more. This is my code and thanks for the help
#include <iostream>
using namespace std;
void main ()
{
int numberone, numbertwo;
char playAgain;
do
{
cout << "Please enter a number: ";
cin >> numberone;
while (numberone < 2)
{
cout << "Sorry, could you please enter a number greater than 1?";
cout << "Please enter a number?";
cin >> numberone;
}
cout << "Please enter another number: ";
cin >> numbertwo;
cout << "The number " << numberone << " has the following divisors:" << endl;
for (int i = 1; i <= (numberone/2); i++)
{
if (numberone % i == 0)
cout << i << ", ";
}
cout << numberone << "." << endl;
if (i/2 =0)
cout << numberone << " has " << " divisors and is a prime number.";
else
cout << numberone << " has " << " divisors and is not a prime number.";
cout << "The number " << numbertwo << " has the following divisors:" << endl;
for (int i = 1; i <= (numbertwo/2); i++)
{
if (numbertwo % i == 0)
cout << i << ", ";
}
cout << numberone << "." << endl;
cout << "Would you like to calculate divisors again? (y/n): ";
cin >> playAgain;
while((playAgain != 'y') && (playAgain != 'Y') &&
(playAgain != 'n') && (playAgain != 'N'))
{
cout << "Please enter a 'y' or 'n'.\n";
cout << "Would you like to calculate divisors again? (y/n): ";
cin >> playAgain;
}
}
while(((playAgain == 'y') || (playAgain == 'Y')));
You are going to have to store the divisors you find for each number in an array or some other STL
container in order to do what you want. Also, are you familiar with functions? Your code would
benefit a lot from functionizing, since you basically wrote the same code twice.
You may as well not store the divisors. You only need to store the number of divisors for each number. I would declare two integer variables, divisor_count1, divisor_count2, initialize them to zero and increment them by one every time I found a divisor for the current number (inside the for-loop).