Note that there are some explanatory texts on larger screens.

plurals
  1. POPrime numbers program
    primarykey
    data
    text
    <p>I'm currently trying out some questions just to practice my programming skills. ( Not taking it in school or anything yet, self taught ) I came across this problem which required me to read in a number from a given txt file. This number would be N. Now I'm suppose to find the Nth prime number for N &lt;= 10 000. After I find it, I'm suppose to print it out to another txt file. Now for most parts of the question I'm able to understand and devise a method to get N. The problem is that I'm using an array to save previously found prime numbers so as to use them to check against future numbers. Even when my array was size 100, as long as the input integer was roughly &lt; 15, the program crashes.</p> <pre><code>#include &lt;cstdio&gt; #include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;fstream&gt; using namespace std; int main() { ifstream trial; trial.open("C:\\Users\\User\\Documents\\trial.txt"); int prime; trial &gt;&gt; prime; ofstream write; write.open("C:\\Users\\User\\Documents\\answer.txt"); int num[100], b, c, e; bool check; b = 0; switch (prime) { case 1: { write &lt;&lt; 2 &lt;&lt; endl; break; } case 2: { write &lt;&lt; 3 &lt;&lt; endl; break; } case 3: { write &lt;&lt; 5 &lt;&lt; endl; break; } case 4: { write &lt;&lt; 7 &lt;&lt; endl; break; } default: { for (int a = 10; a &lt;= 1000000; a++) { check = false; if (((a % 2) != 0) &amp;&amp; ((a % 3) != 0) &amp;&amp; ((a % 5) != 0) &amp;&amp; ((a % 7) != 0)) // first filter { for (int d = 0; d &lt;= b; d++) { c = num[d]; if ((a % c) == 0) { check = true; // second filter based on previous recorded primes in array break; } } if (!check) { e = a; if (b &lt;= 100) { num[b] = a; } b = b + 1; } } if ((b) == (prime - 4)) { write &lt;&lt; e &lt;&lt; endl; break; } } } } trial.close(); write.close(); return 0; } </code></pre> <p>I did this entirely base on my dummies guide and myself so do forgive some code inefficiency and general newbie-ness of my algorithm. Also for up to 15 it displays the prime numbers correctly.</p> <p>Could anyone tell me how I should go about improving this current code? I'm thinking of using a txt file in place of the array. Is that possible? Any help is appreciated.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload