axyd icon

CS172 l5_Ex22-23

axyd | PRO | 04/15/16 02:35:13 AM UTC | 0 ⭐ | 760 👁️ | Never ⏰ | []
C++ |

1.44 KB

|

None

|

0 👍

/

0 👎

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
 
    int fPrime(int);
 
    //Exercise 22
    int main(){
        char repeat = 'y';
        while (repeat == 'y' || repeat == 'Y'){
            int usrIn;
            cout << "\nEnter number to check if it is prime:";
            cin >> usrIn;
 
            if (fPrime(usrIn) == 0) //remainder 0 = NOT prime
                cout << "\nNumber " << usrIn << " is NOT a PRIME.\n\n";
            else //non-prime
                cout << "\nNumber " << usrIn << " is PRIME\n\n";
 
            cout << "Enter (y|Y) to check another number: ";
            cin >> repeat;
        }
        cout << "\nPress enter for problem 23, 100 prime output" << endl;
        cin.get();
        cin.ignore();
 
        //File Block (Exercise 23)
        ofstream outFile;
        string xFile = "1-100_Primes.txt";
        outFile.open(xFile);
        outFile.clear();
        //Find prime and write to file if remainder not 0 (prime)
        for (int x = 1; x <= 100; x++){         
            if (fPrime(x) != 0){
                outFile << x << "\n";
            }
        }
        outFile.close();
        cout << "Output 1-100 primes to: " << xFile << "\n\n";
        system("pause");
        cout << endl;
        return 0;
    }
 
    //Check prime and return single value
    int fPrime(int funcNr){
        int yo;
        if (funcNr == 2) //2 is a prime, using as divider
            return 1;
        else if (funcNr < 2) //no primes below 2
            return 0;
        else{
            for (int ctr = 2; ctr < funcNr; ctr++){ // 2 is first divider over 1                
                if (funcNr % ctr == 0)
                    return 0;
                yo = (funcNr % ctr);
            }
        }
        return yo;
    }

Comments