Advertisement
axyd

CS172 l5_Ex22-23

Apr 14th, 2016
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. using namespace std;
  5.  
  6.     int fPrime(int);
  7.  
  8.     //Exercise 22
  9.     int main(){
  10.         char repeat = 'y';
  11.         while (repeat == 'y' || repeat == 'Y'){
  12.             int usrIn;
  13.             cout << "\nEnter number to check if it is prime:";
  14.             cin >> usrIn;
  15.  
  16.             if (fPrime(usrIn) == 0) //remainder 0 = NOT prime
  17.                 cout << "\nNumber " << usrIn << " is NOT a PRIME.\n\n";
  18.             else //non-prime
  19.                 cout << "\nNumber " << usrIn << " is PRIME\n\n";
  20.  
  21.             cout << "Enter (y|Y) to check another number: ";
  22.             cin >> repeat;
  23.         }
  24.         cout << "\nPress enter for problem 23, 100 prime output" << endl;
  25.         cin.get();
  26.         cin.ignore();
  27.  
  28.         //File Block (Exercise 23)
  29.         ofstream outFile;
  30.         string xFile = "1-100_Primes.txt";
  31.         outFile.open(xFile);
  32.         outFile.clear();
  33.         //Find prime and write to file if remainder not 0 (prime)
  34.         for (int x = 1; x <= 100; x++){        
  35.             if (fPrime(x) != 0){
  36.                 outFile << x << "\n";
  37.             }
  38.         }
  39.         outFile.close();
  40.         cout << "Output 1-100 primes to: " << xFile << "\n\n";
  41.         system("pause");
  42.         cout << endl;
  43.         return 0;
  44.     }
  45.  
  46.     //Check prime and return single value
  47.     int fPrime(int funcNr){
  48.         int yo;
  49.         if (funcNr == 2) //2 is a prime, using as divider
  50.             return 1;
  51.         else if (funcNr < 2) //no primes below 2
  52.             return 0;
  53.         else{
  54.             for (int ctr = 2; ctr < funcNr; ctr++){ // 2 is first divider over 1               
  55.                 if (funcNr % ctr == 0)
  56.                     return 0;
  57.                 yo = (funcNr % ctr);
  58.             }
  59.         }
  60.         return yo;
  61.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement