Changes

Jump to: navigation, search

Team Name (Official)

1,373 bytes added, 22:43, 11 April 2013
Topic
Making parallel an application which calculates the first n primes.
<pre>
//DPS915 Assignment 1
//
//Graeme Smyth (#032-653-081)
//Code written by Graeme Smyth, with inspiration from course Workshop 1
//February 7th, 2013
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;
 
bool isPrime(int x)
{
for(int a = 0; a < x; a++) //a is any integer [0,x)
for(int b = 0; b < x; b++) //b is any integer [0,x)
if(a * b == x) //If a * b = x, then x has two integers that multiply to form it,
return false; //hence x is not prime
 
return true; //If we haven't returned by this point, x must be prime.
}
 
void findPrimes(int* answers, int n)
{
for(int i = 1, primesFound = 0; primesFound < n; i++) //Keep going until we have found n primes
if(isPrime(i)) //Test if "i" is prime
answers[primesFound++] = i; //If it is, record it
}
 
//Main takes one argument, integer n, and calculates the first n primes.
int main(int argc, char* argv[])
{
time_t timeStart, timeEnd;
//Check argument count
if (argc != 2)
{
cerr << "**invalid number of arguments**" << endl;
return 1;
}
 
int n = atoi(argv[1]);
int* answers = new int[n];
timeStart = time(nullptr); //Start timing
 
findPrimes(answers, n);
 
timeEnd = time(nullptr); //Finish timing
 
delete answers;
 
cout << setprecision(3);
cout << "Elapsed time : " << difftime(timeEnd, timeStart) << endl;
}
</pre>
====[[User:Rhotin | Roman Hotin]]====
1
edit

Navigation menu