Write a program that asks the user for an integer and then prints out all its prime 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 or a negative number using a do loop.
#include <iostream>
using namespace std;
bool is_prime(int a){
if(a <= 1) return false;
else if(a == 2) return true;
else{
for(int i = 2; i < a;i++){
if(a % i == 0) return false;
}
return true;
}
}
int main(){
string Input;
int input;
bool flag = false;
do{
cout<<"\nEnter an integer to print prime factors: ";
cin>>Input;
try{
input = stoi(Input);
flag = false;
if(input < 0){
cout<<"\nNon-negative integers only!\n";
flag = true;
}
}
catch(const invalid_argument &a){
cerr<<"\nInvalid input!\n";
flag = true;
}
}while(flag);
for(int i = 2; i <= input; i++){
if(is_prime(i)){
if(input % i == 0){
cout<<i<<endl;
input /= i;
i = 1;
}
}
}
return 0;
}
Comments
Leave a comment