求素數,這是一個“古老”的問題,每個學過編程的人都應該碰到過,這裡是求第M+1到第N個素數,這麼經典的問題,當然得給它寫上一筆,下面是題設要求及代碼實現
1 /*
2 Name:
3 Copyright:
4 Author:
5 Date: 01/04/15 19:19
6 Description:
7 令Pi表示第i個素數。現任給兩個正整數M <= N <= 104,請輸出PM到PN的所有素數。
8
9 輸入格式:
10
11 輸入在一行中給出M和N,其間以空格分隔。
12
13 輸出格式:
14
15 輸出從PM到PN的所有素數,每10個數字占1行,其間以空格分隔,但行末不得有多余空格。
16
17 輸入樣例:
18 5 27
19 輸出樣例:
20 11 13 17 19 23 29 31 37 41 43
21 47 53 59 61 67 71 73 79 83 89
22 97 101 103
23 */
24
25 #include <stdio.h>
26 #include <math.h>
27 #include <stdbool.h>
28
29 void print(int M, int N);
30 bool isprime(int n);
31
32 int main()
33 {
34 int M, N;
35
36 scanf("%d%d", &M, &N);
37 print(M, N);
38
39 return 0;
40 }
41
42 void print(int M, int N)
43 {
44 int i, cnt;
45
46 for(i = 2, cnt = 0; cnt < N; i++)
47 {
48 if(isprime(i))
49 {
50 cnt++;
51
52 if(cnt >= M)
53 {
54 printf("%d", i);
55 if((cnt - M + 1) % 10 != 0 && cnt < N)
56 printf(" ");
57 else
58 printf("\n");
59 }
60 }
61 }
62 }
63
64 bool isprime(int n)
65 {
66 int i, tmp;
67
68 tmp = sqrt(n);
69 for(i = 2; i <= tmp; i++)
70 {
71 if(n % i == 0)
72 return false;
73 }
74
75 return true;
76 }