In: Computer Science
Write a program that asks the user for an integer and then prints out all its factors. For example, when the user enters 84, the program should print 2 2 3 7 Validate the input to make sure that it is not a character or a string using do loop.in c++
#include<iostream>
#include<limits>
using namespace std;
void printFactors(int n)
{
//printing all factors of n
while (n % 2 == 0)
{
cout << 2 << " ";
n = n/2;
}
for (int i = 3; i*i <= n; i = i + 2)
{
while (n % i == 0)
{
cout << i << " ";
n = n/i;
}
}
if (n > 2)
cout << n << " ";
}
int main()
{
//reading input and validating it
int n;
do{
cout<<"Enter a number:";
cin>>n;
if(!cin.fail())
break;
else
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout<<"Enter number only\n";
}
while(1);
printFactors(n);
cout<<endl;
return 0;
}
output:
Enter a number:s
Enter number only
Enter a number:84
2 2 3 7
Process exited normally.
Press any key to continue . . .