c——统计区间内质数

PTA

``` 1 #include<stdio.h>
2 #include<math.h>
3 int prime(int p);
4
5 int main() {
6     int m,n,i;
7     int sum = 0;
8     int count = 0;
9     scanf("%d %d",&m,&n);
10     for(i = m; i <= n; i++) {
11         if(prime(i)) {
12             sum += i;
13             count++;
14         }
15     }
16     printf("%d %d",count,sum);
17 }
18
19 int prime(int p) {
20     int isPrime = 1;
21     int i;
22     if(p < 2) {
23         isPrime = 0;
24     } else {
25         for(i = 2; i <= (int)sqrt(p); i++) {
26             if(p % i == 0) {
27                 isPrime = 0;
28                 break;
29             }
30         }
31     }
32     return isPrime;
33 }```

1、1不是质数，单独考虑

2、判断质数时，除数的条件：i <= (int)sqrt(p)

``` 1 #include<stdio.h>
2 #include<math.h>
3
4 int main() {
5     int m,n,t,p,flag;
6     int sum = 0;
7     int count = 0;
8     scanf("%d %d",&m,&n);
9     t = m;
10     while(t <= n) {
11         p = 2;
12         flag = 0;
13         while(p <= (int)sqrt(t)) {
14             if(t % p == 0) {
15                 flag = 1;
16                 break;
17             }
18             p++;
19         }
20         if(flag == 0) {
21             sum += t;
22             count++;
23         }
24         t++;
25     }
26     printf("%d %d",count,sum);
27 }```

0条评论