Write a C++ program that prompts for an integer greater than one that represents
ID: 3668619 • Letter: W
Question
Write a C++ program that prompts for an integer greater than one that represents the low end of a range and a second integer greater than or equal to the first integer that represents the high end of a range. The program will print the factors of integers in this range in descending order.
For example, if the user enters 2 for the low end of the range and 6 for the high end of the range, then the program will output:
6: 1, 2, 3, 6
5: 1, 5
4: 1, 2, 4
3: 1, 3
2: 1, 2
You should try testing your codes with the above sample output. Here is the code I have so far:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
// Declare and initialize variables
int min; // Minimum integer
int max; // Maximum integer
int i,j; // Variables to use within loops
// Repeatedly prompt for correct input minimum integer
cout << "Enter min integer: ";
cin >> min;
while (min <= 1)
{
cout << "Number must be greater than 1." << endl;
cout << "Enter min integer again: ";
cin >> min;
}
// Repeatedly prompt for correct input maximum integer
cout << "Enter max integer: ";
cin >> max;
while (max < min)
{
cout << "Number must be greater or equal to " << min << "." << endl;
cout << "Enter max integer again: ";
cin >> max;
}
cout << endl;
// Display all factors
for (i = max; i >= min; i--)
{
for (j = 0; j <= i; j++)
{
if (i % j == 0)
{
cout << i << endl;
}
}
cout << "Factors of all numbers in the range: [ " << min << ", " << max << " ]" << endl;
}
// End program
return 0;
}
I am stuck on the step that create the factors. Please help. Thanks a lot!
Explanation / Answer
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
// Declare and initialize variables
int min; // Minimum integer
int max; // Maximum integer
int i,j; // Variables to use within loops
// Repeatedly prompt for correct input minimum integer
cout << "Enter min integer: ";
cin >> min;
while (min <= 1)
{
cout << "Number must be greater than 1." << endl;
cout << "Enter min integer again: ";
cin >> min;
}
// Repeatedly prompt for correct input maximum integer
cout << "Enter max integer: ";
cin >> max;
while (max < min)
{
cout << "Number must be greater or equal to " << min << "." << endl;
cout << "Enter max integer again: ";
cin >> max;
}
cout << endl;
// Display all factors
cout << "Factors of all numbers in the range: [ " << min << ", " << max << " ]" << endl;
for (i = max; i >= min; i--)
{
cout<<i<<": ";
for (j = 1; j < i; j++)
{
if (i % j == 0)
cout << j << ", ";
}
cout<<i<<endl;
}
// End program
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.