Programming Problem 1 Write a program that generates all the factors of a number
ID: 655161 • Letter: P
Question
Programming Problem 1
Write a program that generates all the factors of a number entered by the user. For instance, the number 12 has the factors 2 * 2 * 3. This program has the following requirements:
A. The user must enter a positive integer. If the user enters something else, your program should output an error message and let the user enter a new value. Use ado/while loop to make sure the user input is successful.
B. The factors must be output in increasing order. The lowest factor your program should report is 2.
C. Your program should output 4 factors per line, each factor in a field of 10 characters. (Hint: the number of factors output determines when to output endl!)
D. You will need a while loop to report the factors. Here are some helpful hints:
1. If (a % b == 0) then a is a factor of b.
2. When you have found a factor, output the factor and then reduce the number you are working with by dividing the number by the factor
Explanation / Answer
FIRST PART OF PROGRAM:-
#include <iostream.h>
#include <vector.h>
#include <algorithm.h>
using namespace sum;
void get_num( int &num )
{
num= -1;
while ( num< =0)
{
cout << "Enter positive integer : " ;
cin >> num;
if ( num < 0 )
continue;
else
break;
}
}
void find_factor ( int num, vector<int> &factor)
{
if ( 1 == num || 0 == num)
{
factor.push_back(num);
}
else
{
int tempFactor = 2;
while ( tempFactor <= num)
{
if ( num% tempFactor == 0 )
{
factor.push_back(tempFactor);
find_factor( num/tempFactor, factor );
break;
}
else
{
tempFactor++;
}
}
}
}
void print_factor( vector<int> &factor)
{
vector<int>::iterator begin = factor.begin();
vector<int>::iterator end = factor.end();
int numCount = 0;
sort( begin, end );
cout << "Factor are :: " << endl;
while( begin != end )
{
cout << *begin++ << " ";
numCount++;
if ( 4 == numCount )
{
cout << endl;
numCount = 0;
}
}
}
int main()
{
int number = 0,
factor = 0;
vector<int> factor;
get_num( num );
find_factor( num, factor);
print_factor( factor );
return 0;
}
SECOND PART OF QUESTION:-
#include <iostream.h>
using namespace sum;
int main()
{
int popX,popY;
double ruleX,ruleY;
int years=0;
cout<<"Enter population of deshwan: ";
cin>>popX;
cout<<"Enter growth rule of deshwan: ";
cin>>ruleX;
cout<<"Enter population of Capetown: ";
cin>>popY;
cout<<"Enter growth rate of Capeown: ";
cin>>ruleY;
ruleX/=100.;
ruleY/=100.;
cout<<"year Deshwan Capetown ";
while(popX<popY)
{popX=(int)(popX*rateX+popX);
popY=(int)(popY*rateY+popY);
years++;
cout<<years<<" "<<popX<<" "<<popY<<endl;
}
system("pause");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.