Primes.cpp

  1. /*
  2. Primes.cpp — Francisco Cascales — 2017-12-08
  3.  
  4. $ sudo apt-get install build-essential
  5. $ g++ Primes.cpp -o Primes.exe
  6. $ ./Primes
  7. */
  8.  
  9. #include <iostream>
  10.  
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13.  
  14. //using namespace std;
  15.  
  16. //-----------------------------------------------
  17.  
  18. class Primes {
  19.  
  20. const static int PRIMES_PER_FILE = 1000000;
  21. const static int NUM_FILES = 50;
  22.  
  23. private:
  24. int numfile;
  25. int numprime;
  26. FILE *file = NULL;
  27. char *line = NULL;
  28.  
  29. public:
  30. Primes() {
  31. numfile = 0;
  32. numprime = 0;
  33. open();
  34. }
  35. bool hasNext() {
  36. if (numfile < NUM_FILES) return true;
  37. else if (numprime < PRIMES_PER_FILE) return true;
  38. else return false;
  39. }
  40. int next() {
  41. if (numprime >= PRIMES_PER_FILE) {
  42. close();
  43. open();
  44. }
  45. numprime++;
  46. return nextLine();
  47. }
  48. void close() {
  49. fclose(file);
  50. //if (line) free(line); // Da error
  51. }
  52.  
  53. private:
  54. void open() {
  55. numfile++;
  56. numprime = 0;
  57. char filename[40];
  58. sprintf(filename, "primes/primes%d.txt", numfile);
  59. file = fopen(filename, "r"); if (file == NULL) exit(1);
  60. }
  61. long nextLine() {
  62. size_t len;
  63. if (getline(&line, &len, file) == -1) return 0;
  64. char *ptr;
  65. return strtol(line, &ptr, 10);
  66. }
  67.  
  68. }; // class
  69.  
  70. //-----------------------------------------------
  71.  
  72. /*int main() {
  73. Primes primes;
  74. while (primes.hasNext()) {
  75. long prime = primes.next();
  76. cout << prime << "\n";
  77. if (prime > 1000) break;
  78. }
  79. primes.close();
  80. }*/
  81.  

Proinf.net