Search code examples
c++prime-factoring

C++ Program for Prime Factors


I'm trying to build a program that asks to user to input a positive integer and then the prime factors of this number are outputted. I'm giving the user three attempts to enter a valid input or the program ends. So any negative integers and non integers as well as other characters such as letters will give an error message. I'm nearly there but my output won't behave as I want. It treats decimal numbers as integers and negative numbers aren't returning the error.

#include <iostream>
#include <iomanip>
#include <cmath>
#include <stdio.h>

using namespace std;

int main()
{
    int num,i,flag,n;



    //executes loop if the input fails (e.g., no characters were read)
    while (cout << "Enter a number: " && !(cin >> num)) 
    {
        cin.clear(); //clear bad input flag
        cin.ignore(numeric_limits<streamsize>::max(), '\n'); //discard input
        cout << "Invalid input, please re-enter: \n";
    }

    i=2;
    n=num;
    cout<< "\nThe Prime factors of "<< num << " are:"<< endl;
    while(i<=num)
    {
        flag=0;
        while(n%i==0)
        { 
            n=n/i;
            flag++;
        }
        if(flag>0)
        {
            cout <<i<< endl;
        }
        ++i;
     }


     system("PAUSE");
     return 0;
}

Solution

  • You are not getting an error for entering a negative number as you are not checking for that in you input validation. You could add into your while condition to check for a negative output as:

    while (cout << "Enter a number: " && (!(cin >> num) || num <= 0)) 
    

    The reason you do not catch input of a decimal number is cin successfully converts and stores the input up to the decimal point and then stops, leaving the remainder of the input in the buffer. We can see that with:

    #include <iostream>
    
    int main() 
    {
        int foo;
        double bar;
        std::cin >> foo;
        std::cin >> bar;
        std::cout << foo << std::endl;
        std::cout << bar;
    }
    

    Input:

    5.82
    

    Output:

    5
    0.82
    

    Live Example

    You could include a check in your while loop condition to see if there is more input waiting in the stream with

    while (cout << "Enter a number: " && (!(cin >> num) || num <= 0 || cin.get() != '\n'))
    

    As for looping only three times you can add a counter to the program and increment the counter each time the body of the loop executes. Once the counter gets to 3 then you would exit the program

    int counter = 0;
    while (cout << "Enter a number: " && (!(cin >> num) || num <= 0 || cin.get() != '\n'))
    {
        if (counter == 3)
            return 0;  // exit
        cin.clear(); //clear bad input flag
        cin.ignore(numeric_limits<streamsize>::max(), '\n'); //discard input
        cout << "Invalid input, please re-enter: \n";
        counter++;
    }