Answer to Question #183284 in C++ for Mridul

Question #183284

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. 


1
Expert's answer
2021-04-20T00:53:57-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS