- #1

Kalouste

- 21

- 0

I've written an algorithm that has the following goal: finding all prime numbers up to a specified integer. I've made two different algorithms actually: on one hand, I've used the concept beyond the ancient sieve of eratosthenes; on the other, I've used a function called isprime() that tests if a number is prime. For instance, let's say I want to determine which method is faster. So I need to time a piece of code in each algorithm.

As an example, here's the code of the first algorithm:

I've omitted the isprime() function definition, because I felt it's unnecessary. The problem with this approach is that my computer writes the numbers so rapidly that I probably will need to write the time in milliseconds if I wanted the algorithm to write every prime number up to a small number, as 11. Is there a function that allows me to do that?

Thank you on advance.

"[URL

As an example, here's the code of the first algorithm:

Code:

```
#include <stdio.h>
#include <math.h>
#include <time.h>
int isprime(int num);
int main () {
int n, num;
time_t t1, t2;
printf("Enter a number\n");
while (scanf("%d", &n) != 1) {
printf("Error: Try again.\n");
while (getchar() != '\n')
;
}
printf("Prime numbers\n");
time(&t1);
for (num = 2; num <= n; num += 1) {
if (isprime(num) == 1)
printf("%d\n", num);
}
time(&t2);
printf("Time elapsed: %f ms\n", (float)(t2-t1));
return 0;
}
```

I've omitted the isprime() function definition, because I felt it's unnecessary. The problem with this approach is that my computer writes the numbers so rapidly that I probably will need to write the time in milliseconds if I wanted the algorithm to write every prime number up to a small number, as 11. Is there a function that allows me to do that?

Thank you on advance.

__Links I've consulted__"[URL

Last edited by a moderator: