A summary of the operations: Positive or Negative: number > 0 Even or Odd: number % 2 == 0 Prime or Composite:
Even Odd Prime Composite Positive Negative Factors |
main.cpp |
#include <iostream> #include <vector> #include <string> using namespace std; int main(void) { long long int number = 0; //number input by user unsigned long long int count = 0; //count of factors vector<unsigned int long>factor; bool badInput = false; bool isNumberNegative = false; string tempInput; do { //HANDLE IF USER INPUT A NON-NUMBER if (badInput == true) { cout << "Bad user input.\n"; tempInput.clear(); cin.clear(); //clear error flag //ignore entire input cin.ignore(numeric_limits<streamsize>::max(), '\n'); } //PROMPT USER FOR NUMBER cout << "Enter a whole number to examine: "; //get user input to tempInput cin >> tempInput; badInput = false; //loop through each character of tempInput for (unsigned int i = 0; i < tempInput.length(); i++) { //test if character is digit if (!isdigit(tempInput.at(i))) { //if fails digit check set bad input flag and escape badInput = true; //breaks us out of for loop, we could also set i to length + 1 break; } else { badInput = false; } } //having parsed the user input, store it as a number if (badInput == false) { number = stoll(tempInput); } } while (badInput == true); cout << '\n' << number << " is "; //TEST IF NEGATIVE OR POSITIVE if (number < 0) { cout << "negative"; isNumberNegative = true; } else if ( number > 0) { cout << "positive"; } else // must be zero { cout << "neither negative or positive"; } //TEST IF EVEN OR ODD //since even numbers are divisible by two with no remainder, //we use modulus to check if number divided by 2 has remainder. if (number % 2 == 0) { cout << ", is even, "; } else { cout << ", is odd, "; } //TEST IF PRIME OR COMPOSITE // prime is a positive integer that has exactly two positive divisors // 0 and 1 are neither prime nor composite //Negative numbers are not prime or composite, so we don't test. if (isNumberNegative || number == 0 || number == 1) { cout << "is not prime or composite"; } else { //go through each integer, from one to the user's number. for (long long int i = 1; i < number; i++) { //test if user's number is divisible by current iteration (i). if (number % i == 0) { //increment the count of factors. count++; //the current number is a factor, store it in the stack factor.push_back(i); } } //TEST IF COMPOSITE OR PRIME //if the count of factors is more than one, it must be composite. if (count > 1) { cout << "composite"; } else { cout << "prime"; } } //OUTPUT FACTORS cout << " and has " << factor.size() << " factors:\n"; for (unsigned int i = 0; i < factor.size(); i++) { cout << factor.at(i) << '\n'; } //delete factors, if any, - tidy up factor.clear(); //holds screen so we can view results cout << "\nEnter character and press enter to exit."; cin >> number; return 0; } |
No comments:
Post a Comment