axyd

CS172 l5_Ex22-23

Apr 6th, 2016
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <ctime>
  4. #include <cstdlib>
  5. using namespace std;
  6.  
  7. namespace nsEx22_23{
  8.     int isPrime(int);
  9.  
  10.     //Exercise 22
  11.     int intEx22(){
  12.         int iin;
  13.         cout << "\nEnter number to check if it is prime:\t";
  14.         cin >> iin;
  15.  
  16.         if (isPrime(iin) != 0)  //prime
  17.             cout << "\nThe number " << iin << " is Prime\n\n";
  18.         else //non-prime
  19.             cout << "\nThe number " << iin << " is NOT Prime.\n\n";
  20.  
  21.         cout << "\t\tPress <enter> to continue to problem 23\n";
  22.         cin.get();
  23.         cin.ignore();
  24.         return 0;
  25.     }
  26.  
  27.     //Exercise 23
  28.     int intEx23(){
  29.         //Prime the file (open and clear)
  30.         ofstream outFile;
  31.         string strFN = "Primes_1-100.txt";
  32.         outFile.open(strFN);
  33.         outFile.clear();
  34.  
  35.         //Prime Finder
  36.         for (int x = 1; x <= 100; x++){        
  37.             if (isPrime(x) != 0){ //prime
  38.                 outFile << x << "\n";
  39.             }
  40.         }
  41.             outFile.close();
  42.             cout << "\t>>> Primes between 1-100 were written to: " << strFN << " <<<\n\n";
  43.             system("pause");
  44.             cout << endl;
  45.             return 0;
  46.     }
  47.  
  48.     //Prime Checker function
  49.     int isPrime(int num1){
  50.         for (int num2 = 2; num2 <= sqrt(num1); num2++){ // >1 because every number is divisible by 1
  51.             num1 %= num2;
  52.             if ((num1 % num2) == 0) //not prime
  53.                 break;
  54.         }
  55.         return num1; //return remainder
  56.     }
  57. }
Add Comment
Please, Sign In to add comment