原代碼核心錯誤
void fun(int m, int k, int xx[]) {
int j, n=0, a, b=0;
while(n < k) {
a = m + 1; // 錯誤 1:a 每次循環重置為 m+1,導致死循環
for(j=1; j 0
if(a%j==0) b++;
if(b==0) xx[n++] = a; // 永不成立
}
xx[n] = 0;
}
修正版:求 m 之後的 k 個質數
void fun(int m, int k, int xx[]) {
if (!xx || k <= 0) return;
int n = 0;
int candidate = m + 1;
if (candidate <= 2) { xx[n++] = 2; candidate = 3; } // 2 是唯一偶質數
while (n < k) {
int isPrime = 1;
int limit = (int)sqrt(candidate);
for (int j = 3; j <= limit; j += 2) { // 只試奇數因子
if (candidate % j == 0) { isPrime = 0; break; }
}
if (isPrime) xx[n++] = candidate;
candidate += 2; // 跳過偶數
}
xx[n] = 0; // 結束標記
}
關鍵優化點
- 候選數遞增:
candidate 在循環外遞增,而非重置。
- 試除優化:只試除到
sqrt(candidate),且跳過偶數。
- 邊界處理:正確處理 2 這個特殊質數。
- 參數校驗:防止空指針、非正 k 導致崩潰。
文件讀寫部分建議
- 使用
fscanf/fprintf 時檢查返回值,確保讀寫成功。
- 動態分配緩衝區或使用足夠大的固定數組,避免溢出。
- 關閉文件前
fflush 確保數據落盤。