0

## c語言課程作業問題

``````#include <stdio.h>
#include <time.h>

int main() {
double z = 0;
while(z<3){
int i = 1;int j;
enum boolean isprime;
enum boolean {false,true};
clock_t i,j;
double z;
i=clock();
j=clock();
isprime = true;
switch(i){
case 1 :
isprime =false;
break;
case 2 :
break;
default :
for(j=2;j<i;j++){
if((i%j)==0){
isprime = false;
break;
}
else;
}
z=(double)(j-i);
printf("Use Time:%f\n",(z/CLOCKS_PER_SEC));
}
}
}
``````

dragonH iT邦超人 5 級 ‧ 2020-09-28 20:54:25 檢舉
image in image out

```
```

### 3 個回答

1

iT邦大師 1 級 ‧ 2020-09-28 21:52:54

``````這是程式碼
``````

``````int i = 1;int j;
``````
``````clock_t i,j;
``````

enum的用法可以參考 列舉 (C++)

1

iT邦新手 2 級 ‧ 2020-09-29 05:54:26

``````#include <stdio.h>
#include <time.h>

int prime(int n) {
int i, flag = 1;
for(i = 2; i * i <= n; i++) {
if(!(n % i)) {
flag = 0;
break;
}
}
return flag;
}

int main() {
int a, b;
printf("請輸入兩個整數: ");
scanf("%d %d", a, b);
int start = clock();
prime(a); prime(b);
while (clock() < CLOCKS_PER_SEC * 3 - start) {}
printf("Use Time:%f\n", difftime(start, clock()));
return 0;
}
``````

QRG%Vhah4A\$@HKL

QAQ

484我們都誤會你老師了?u?

0

iT邦大神 1 級 ‧ 2020-09-29 21:25:42

``````#include <stdio.h>
#include <time.h>
int prime(long int n) {
long int i, flag = 1;
for(i = 2; i * i <= n; i++) {
if(!(n % i)) {
flag = 0;
break;
}
}
return flag;
}

int main() {
long int n = 5000000;
long int previous_n;
clock_t start_t, end_t;
double diff_t = 0;
start_t = clock();
while ((n < 5000100)&&(diff_t < 3.0)) {
if (prime(n)>0) {
end_t = clock();
diff_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
// if (diff_t >= 3.0) {
printf("It cost %.5f seconds between finding prime %d and %d\n", diff_t, previous_n, n);
// }
start_t = clock();
previous_n = n;
} else {
// printf("%d is not prime.\n", n);
}
n++;
}
return 0;
}
``````

``````#include <stdio.h>
#include <time.h>
int prime(long int n) {
long int i, flag = 1;
// for(i = 2; i * i <= n; i++) {
for(i = 2; i < n; i++) {
if(!(n % i)) {
flag = 0;
// break;
}
}
return flag;
}

int main() {
long int n = 1;
long int previous_n;
clock_t start_t, end_t;
double diff_t = 0;
start_t = clock();
while ((n < 60000)&&(diff_t < 3.0)) {
if (prime(n)>0) {
end_t = clock();
diff_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
if (diff_t >= 3.0) {
printf("It cost %.5f seconds between prime 1 and %d\n", diff_t, n);
}
// start_t = clock();
previous_n = n;
} else {
// printf("%d is not prime.\n", n);
}
n++;
}
return 0;
}
``````