Add new exercises. 09-12

This commit is contained in:
juan 2022-09-12 16:56:48 +08:00
parent a263ec034a
commit 40e49bc2d4
No known key found for this signature in database
GPG key ID: 5C1E5093C74F1DC7
2 changed files with 153 additions and 0 deletions

View file

@ -0,0 +1,37 @@
#include <math.h>
#include <stdio.h>
#include <time.h>
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;
}

View file

@ -0,0 +1,116 @@
#include <stdio.h>
#include <time.h>
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");
}
}