[題目]
在小於10的素數中有3、5、7組成的等差數列,在小於30的素數中有11、17、23、29組成的等差數列。
試找出區間[100,1000]內的素數構成的最大等差數列(即等差數列包含的素數個數最多)並打印輸出。
[關鍵字]
素數;等差數列
[思路]
- 先用一個數組標記出 100 ~ 1000 之間哪些是素數;
- 差值從 2 ~ 900 進行循環判斷
[實現]
1 #include <stdio.h> 2 #define N 1001 3 #define MAX_CHA 900 4 5 void isPrime(int* num); // 判斷素數 6 void getMax(int* num); // 獲取最長等差數列 7 8 int main(void){ 9 int num[N] = {0}; 10 11 isPrime(num); 12 getMax(num); 13 14 return 0; 15 } 16 17 void isPrime(int* num){ 18 int i, j; 19 20 // i取值從3 ~ N, 判斷是否是素數 21 // 素數標記 1, 合數標記為 0 22 for (i = 3; i <= N; i++){ 23 num[i] = 1; 24 for (j = 2; j < i; j++){ 25 if (i % j == 0){ 26 // 說明是合數, 跳出本for循環,開始判斷下一個數 27 num[i] = 0; 28 break; 29 } 30 } 31 } 32 33 } 34 35 void getMax(int* num){ 36 37 int cha; // 差值 38 int i, j, k; 39 int count; // 記錄長度 40 int lastCount = 0; 41 int lastCha, start; 42 // 差值取值從 2 ~ 900 43 for (cha = 2; cha <= MAX_CHA; cha++){ 44 // 從101開始,找出最長 素數等差數列 45 for (i = 101; i <= N; i++){ 46 count = 0; // count重置為 0 47 // 中間可能存在更長的數列 48 for (j = i; j <= N; j ++){ 49 for (k = j; k <= N; k += cha){ 50 if (num[k]){ 51 count++; // 長度加 1 52 }else{ 53 // 等差數列斷掉,從下一個數開始 54 // 是否找到更長的等差數列 55 if (count > lastCount){ 56 lastCount = count; 57 lastCha = cha; 58 start = j; 59 } 60 count = 0; // count重置為 0 61 break; 62 } 63 } 64 65 } 66 } 67 68 } 69 /* 70 printf("lastCount=%d\n", lastCount); 71 printf("start=%d\n", start); 72 printf("lastCha=%d\n", lastCha); 73 */ 74 75 for (i = 0; i < lastCount; i++){ 76 printf("%d ", start); 77 start += lastCha; 78 } 79 printf("\n"); 80 }
[結果]
107 137 167 197 227 257
[討論]
有更好的做法歡迎和我討論,我的微信號:lemonnooo