Guest User

Untitled

a guest
Dec 11th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. /**
  2. Shade Alabsa
  3. isPrime
  4. Cycles through the numbers 1-100 and uses isPrime to calculate if a number is prime. This is a very rudimentary algorithm to fix it but I didn't want to figure our arrays in c++ right now to implement a proper sieve of eratosthenes algorithm.
  5.  
  6. */
  7. #include <iostream>
  8. #include <fstream>
  9. using namespace std;
  10.  
  11. //Calcaulates if a number is prime by mod division
  12. bool isPrime(int);
  13.  
  14. int main(){
  15.  
  16.     ofstream prime_list; //creates a file stream to write the data to
  17.     prime_list.open("prime_list.txt"); //creates a file called prime_list.txt
  18.     prime_list << "List of Prime Numbers under 100. \n"; //headed for prime_list file
  19.     prime_list << "1\n"; //we know 1-3 are all prime numbers so might as well and add them now so we can cycle through less numbers.
  20.     prime_list << "2\n";
  21.     prime_list << "3\n";
  22.  
  23.     for(int i = 5;i<=100;i+=2){ //we start cycling through the numbers. We started at 5 since we know 1-3 are all primes and any even number is composite. That's also why we add 2 to every prime so we can skip it
  24.         if(isPrime(i)){
  25.             prime_list << i << endl; //if the number is prime it writes it to the file
  26.         }
  27.     }
  28.    
  29.     prime_list.close();
  30.     return 0;
  31. }
  32.  
  33. /**
  34. Calculates the midpoint of the number passed it, any number won't be divisible by anything that is equal to half of it. Then it cycles from 2, just as a precaution or if you want to reuse this function for later, to see if a
  35. number can divide into the passed in number evenly. Takes 1 argument, the number we are testing to see if it's prime, and returns a boolean value saying it's a prime or not.
  36. */
  37. bool isPrime(int num){
  38.     int mid = num /2 +1;
  39.     bool prime = true;
  40.  
  41.     for(int i = 2; i<= mid;i++){
  42.         if(num % i == 0){
  43.             prime = false;
  44.         }
  45.     }
  46.  
  47.     return prime;
  48. }
Add Comment
Please, Sign In to add comment