axyd icon

CS172 l5_Ex22-23

axyd | PRO | 04/06/16 05:23:26 AM UTC | 0 ⭐ | 589 👁️ | Never ⏰ | []
C++ |

1.25 KB

|

None

|

0 👍

/

0 👎

#include <iostream>
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
 
namespace nsEx22_23{
    int isPrime(int);
 
    //Exercise 22
    int intEx22(){
        int iin;
        cout << "\nEnter number to check if it is prime:\t";
        cin >> iin;
 
        if (isPrime(iin) != 0)  //prime
            cout << "\nThe number " << iin << " is Prime\n\n";
        else //non-prime
            cout << "\nThe number " << iin << " is NOT Prime.\n\n";
 
        cout << "\t\tPress <enter> to continue to problem 23\n";
        cin.get();
        cin.ignore();
        return 0;
    }
 
    //Exercise 23
    int intEx23(){
        //Prime the file (open and clear)
        ofstream outFile;
        string strFN = "Primes_1-100.txt";
        outFile.open(strFN);
        outFile.clear();
 
        //Prime Finder
        for (int x = 1; x <= 100; x++){         
            if (isPrime(x) != 0){ //prime
                outFile << x << "\n";
            }
        }
            outFile.close();
            cout << "\t>>> Primes between 1-100 were written to: " << strFN << " <<<\n\n";
            system("pause");
            cout << endl;
            return 0;
    }
 
    //Prime Checker function
    int isPrime(int num1){
        for (int num2 = 2; num2 <= sqrt(num1); num2++){ // >1 because every number is divisible by 1
            num1 %= num2;
            if ((num1 % num2) == 0) //not prime
                break;
        }
        return num1; //return remainder
    }
}

Comments