Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // main.cpp
- // Pi Generator
- //
- // Created by Nikolaj Ignatieff Schwartzbach on 2/6/13.
- // Copyright (c) 2013 Nikolaj Ignatieff Schwartzbach. All rights reserved.
- //
- #include <iostream>
- #include <math.h>
- #include <time.h>
- using namespace std;
- int limit=0;
- int p=2;
- int nextPrime=5;
- void writeNumber(int ix){
- int j , i = 0, k = 0;
- if( ix < 0){cout << '-';ix *= -1;}
- int temp = ix;
- int p = 1;
- while( temp > 0){temp /= 10;p *= 10;i++;}
- j = i % 3;
- p /= 10;
- while( i > 0 ){
- cout << char ((ix/p) +'0');
- ix %= p;p /= 10;i--;k++;j--;
- if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2)){cout <<".";k = 0;}}
- }
- int main(int argc, const char * argv[])
- {
- clock_t t1, t2;
- int isPrime, i, nxtSQR, limit;
- cout << "Amount of primes to find: ";
- cin >> limit;
- if(cin.fail()) cout << "Non-numeric input detected. Action aborted.";
- cout << "Finding ";
- writeNumber(limit);
- cout << " primes..." << endl << endl;
- int* primes = new int[limit];
- primes[0]=2;
- primes[1]=3;
- t1 = clock();
- while(p<limit){
- nxtSQR = sqrt(nextPrime);
- isPrime=true;
- for(i=0;i<limit;i++){
- if(primes[i]==0 || primes[i]>nxtSQR) break;
- if(nextPrime % primes[i] == 0){isPrime=false;break;}}
- if(isPrime){primes[p]=nextPrime;p++;} nextPrime+=2;
- if(nextPrime % 5 == 0)nextPrime+=2;
- }
- t2 = clock();
- float diff = ( (float)t2 - (float)t1) / 1000000 ;
- cout << "Execution Time: " << diff << " seconds.\n";
- cout << "Highest prime: ";
- writeNumber(primes[limit-1]);
- cout << endl;
- system( "read -n 1 -s -p \"Press any key to continue...\"" );
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement