Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- Shade Alabsa
- isPrime
- 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.
- */
- #include <iostream>
- #include <fstream>
- using namespace std;
- //Calcaulates if a number is prime by mod division
- bool isPrime(int);
- int main(){
- ofstream prime_list; //creates a file stream to write the data to
- prime_list.open("prime_list.txt"); //creates a file called prime_list.txt
- prime_list << "List of Prime Numbers under 100. \n"; //headed for prime_list file
- 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.
- prime_list << "2\n";
- prime_list << "3\n";
- 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
- if(isPrime(i)){
- prime_list << i << endl; //if the number is prime it writes it to the file
- }
- }
- prime_list.close();
- return 0;
- }
- /**
- 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
- 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.
- */
- bool isPrime(int num){
- int mid = num /2 +1;
- bool prime = true;
- for(int i = 2; i<= mid;i++){
- if(num % i == 0){
- prime = false;
- }
- }
- return prime;
- }
Add Comment
Please, Sign In to add comment