Results 1 to 2 of 2

Thread: Finding nth prime

  1. #1

    Thread Starter
    Fanatic Member Flashbond's Avatar
    Join Date
    Jan 2013
    Location
    Istanbul
    Posts
    646

    Finding nth prime

    Actually this was something for C++ codebank. Not the fastest but an elegant code written by me.

    Code:
    // This code was written by Mert Ener
    #include <time.h>
    #include <iostream>
    
    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[n+1]=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.");}
    Last edited by Flashbond; Mar 20th, 2013 at 05:49 AM.

  2. #2

    Thread Starter
    Fanatic Member Flashbond's Avatar
    Join Date
    Jan 2013
    Location
    Istanbul
    Posts
    646

    Re: Finding nth prime

    Finally, it is a shortened and stable version of my original code.
    Code:
    // written by Mert Ener
    int k = "the nth prime you like" -1;
    int l,m=1,n,o;
    int*p;p=new int [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,
    Code:
    int k = "the nth prime you like" -1;
    int l,m=1,n,o;
    int*p;p=new int [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.
    Last edited by Flashbond; Mar 21st, 2013 at 04:31 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width