repl.it
@tomnagel/

Find primenumber

C++

No description

fork
loading
Files
  • main.cpp
  • currentnumber_file
  • main
  • primenumber_file
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <fstream> //Used for files
#include <string> // Used for strings
#include <ctime> //Used for tracking time
std::fstream primenumber_file("primenumber_file"); //std::ios_base::in std::ios::app
std::fstream currentnumber_file("currentnumber_file");

bool is_multiple(long long primenumber,long long currentnumber){
  if ((currentnumber % primenumber) == 0){
    return true;
  }
  else return false;
}

bool is_this_a_primenumber(long long currentnumber){
  long long primenumber;
  primenumber_file.close();
  primenumber_file.open("primenumber_file", std::ios_base::in); //changes mode to read
  primenumber_file.clear(); //needed for return pointer
  primenumber_file.seekg(0, std::ios::beg); //return pointer to start of file
  while(primenumber_file >> primenumber){ //goes through all primenumbers
    if (is_multiple(primenumber, currentnumber)){ //calls is_multiple to check
      primenumber_file.close();
      return false; //no prime number
    }
  }
  primenumber_file.close();
  return true; // a prime number
}

int main() {
  std::cout << "Enter how long you want the program to run (in sec):";
  int end_time;
  std::cin >> end_time;
  end_time = end_time + std::time(nullptr); //moment in time when program should stop
  if (primenumber_file.is_open() and currentnumber_file.is_open()){
    long long currentnumber; //needs long long because size int is to small
    while(end_time > std::time(nullptr)){ //runs until end time is reached
      currentnumber_file >> currentnumber; //gets our number out of file
      if (is_this_a_primenumber(currentnumber)){ //cals function and checks result
        primenumber_file.close();
        primenumber_file.open("primenumber_file", std::ios::app);
        primenumber_file << " " << currentnumber ; //write new prime number to file
        primenumber_file.close();
      }
      currentnumber = currentnumber + 1;
      remove("currentnumber_file"); //deletes old file
      std::ofstream currentnumber_file("currentnumber_file"); //creates new file
      currentnumber_file << currentnumber; //writes our number to the new file
    }
    primenumber_file.close(); //closes files
    currentnumber_file.close();
  }  
  else std::cout << "Unable to open files";
  return 0;
}
Fetching token
?