diff --git a/semester3/exercises/exercise2.13.c b/semester3/exercises/exercise2.13.c new file mode 100644 index 0000000..61a3a39 --- /dev/null +++ b/semester3/exercises/exercise2.13.c @@ -0,0 +1,37 @@ +#include +#include +#include + +void printTime(clock_t end, clock_t start) { + printf("Took %lf to calculate.\n", ((double)(end - start)) / CLOCKS_PER_SEC); +} + +void calculate(long long N) { + clock_t end, start; + + start = clock(); + + for (int i = 1, root = (int)floor(sqrt((double)N)); i < root; i++) { + if (N % i == 0) { + end = clock(); + printTime(end, start); + printf("%lld is not prime\n", N); + return; + } + } + + end = clock(); + printTime(end, start); + printf("%lld is prime\n", N); + return; +} + +int main(void) { + long long test[] = {1048575, 1099511627775}; + for (int i = 0; i < 2; i++) { + calculate(test[i]); + printf("\n"); + } + + return 0; +} diff --git a/semester3/exercises/exercise2.6.c b/semester3/exercises/exercise2.6.c new file mode 100644 index 0000000..b62bcbc --- /dev/null +++ b/semester3/exercises/exercise2.6.c @@ -0,0 +1,116 @@ +#include +#include + +int counter = 0; + +void getTime(int N, clock_t start_t, time_t end_t) { + double runningTime; + runningTime = ((double) (end_t - start_t)) / CLOCKS_PER_SEC; + + printf("%d: Took %lf sec\n", counter++, runningTime); +} + +void test(int N) { + clock_t start_t; + clock_t end_t; + int sum; + + // 1 + sum = 0; + + start_t = clock(); + + for (int i = 0; i < N; i++) { + sum++; + } + + end_t = clock(); + + getTime(N, start_t, end_t); + + // 2 + start_t = clock(); + sum = 0; + + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + sum++; + } + } + + end_t = clock(); + + getTime(N, start_t, end_t); + + // 3 + start_t = clock(); + sum = 0; + + for (int i = 0; i < N; i++) { + for (int j = 0; j < N * N; j++) { + sum++; + } + } + + end_t = clock(); + getTime(N, start_t, end_t); + + // 4 + start_t = clock(); + + sum = 0; + + for (int i = 0; i < N; i++) { + for (int j = 0; j < i; j++) { + sum++; + } + } + + end_t = clock(); + getTime(N, start_t, end_t); + + // 5 + start_t = clock(); + + sum = 0; + + for (int i = 0; i < N; i++) { + for (int j = 0; j < i * i; j++) { + for (int k = 0; k < j; k++) { + sum++; + } + } + } + + end_t = clock(); + getTime(N, start_t, end_t); + + // 6 + start_t = clock(); + + sum = 0; + + for (int i = 1; i < N; i++) { + for (int j = 1; j < i * i; j++) { + if (j % i == 0) { + for (int k = 0; k < j; k++) { + sum++; + } + } + } + } + + end_t = clock(); + getTime(N, start_t, end_t); +} + +int main(void) { + int times[] = {5, 10, 100, 250}; + + for (int i = 0; i < 4; i++) { + counter = 0; + printf("N = %d\n\n", times[i]); + test(times[i]); + printf("\n"); + } +}