0

## [新手]c語言課程作業問題

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

int main() {
enum boolean isprime;
enum boolean {false,true};
double z = 0;
while(z<3){
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));
}
}
}
``````

enum boolean isprime;
enum boolean {false,true};

...
#include <stdbool.h>
int main() {
bool isPrime;
...
}

### 2 個回答

0

iT邦新手 3 級 ‧ 2020-09-29 20:59:18

0

iT邦大神 1 級 ‧ 2020-09-29 21:22:31

``````#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;
}
``````