// This code was written by Mert Ener
#include <time.h>
#include <iostream>
// Requires a run button on Windows form.
private: System::Void button1_Click_1(System::Object^ sender, System::EventArgs^ e) {
UInt64 cloc = clock();
long o, m = 1;
long k = long::Parse(textBox1->Text)-2; // The textbox you entered for the nth prime.
vector<int> p(1,2);
for( long n = 0; n <= k; n++ ) {
m += 2;
for( long l = 1;o=p[l],o*o<=m; l++ ) {
if (m % p[l] == 0) {
m += 2;
l=0;}}
p.push_back(m);}
textBox2->Text = p[k+1].ToString(); // The textbox for the result.
MessageBox::Show("It took me " + (clock() - cloc).ToString() + " milliseconds to find your prime.");}
Looks like C++\CLI - Microsoft's managed version of C++.
It is a code written with VS2012 in C++.Net. It is for a windows userform with two textboxes and line 6 represents a click to run button.
The core of the code is here
1 2 3 4 5 6 7 8 9 10 11
long o,m = 1;
long k = "nth prime you like";
vector<int> p(1,2);
for( long n = 0; n <= k; n++ ) {
m += 2;
for( long l = 1;o=p[l],o*o<=m; l++ ) {
if (m % p[l] == 0) {
m += 2;
l=0;}}
p.push_back(m);}
"The result is" = p[k+1]
Yeah, your code also looks cool! In the forums, it has been said 4 sec. is a optimistic result for 1000000th prime. My code finds in less than 2 seconds on an ordinary pc.
Finally, it is a shortened and stable version of my original code.
1 2 3 4 5 6 7 8
int k = "the nth prime you like" -1;
int l,m=1,n,o;
int*p;p=newint [k+1],p[0]=2;
for(n=1;m+=2,n<=k;p[n]=m,n+=1)
for(l=1,o=3;o*o<=m;(m%o==0)?(m+=2,l=1,o=3):(l+=1,o=p[l]));
"the result" = p[k]
In fact the exact expression of my original code is this below. Even it is a shorter and slightly faster way,
1 2 3 4 5 6 7 8
int k = "the nth prime you like" -1;
int l,m=1,n,o;
int*p;p=newint [k+1],p[0]=2;
for(n=1;m+=2,n<=k;p[n]=m,n++)
for(l=1;o=p[l],o*o<=m;(m%o==0)?(m+=2,l=1):(l++));
"the result" = p[k]
however it is unstable because of memory initialization issues and I couldn't overcome it. After 1000000th query it is giving division-by-zero error. Sometimes o gets 0 value even there is nothing such as 0 in array p. I can prove it because it runs so well around 1000000th queries. And m%0 causes the error. That's why I had to secure o many times in the first code. If someone can handle it, will be my welcome.
But the first code runs perfectly for 10000000th query around 40 seconds on an ordinary pc.
Wowww, It is amazing! I didn't know about that "Sieve of Eratosthenes" therorem. It works around10 times faster than my code! Amsome ;) It has some logarithmic expressions. I'll inspect this.