當前位置:首頁 » 編程語言 » c語言判斷一個數是否是素數

c語言判斷一個數是否是素數

發布時間: 2024-11-05 01:36:32

A. c語言如何判斷一個數是整數還是素數

以下是判斷代碼:
#include <math.h>
#include <stdio.h>

int is_prime(int num) {
if (num <= 1) {
return 0; // 小於等於1的數不是素數
}
if (num <= 3) {
return 1; // 2和3是素數
}
if (num % 2 == 0 || num % 3 == 0) {
return 0; // 排除能被2或3整除的數
}
// 只需檢查到sqrt(num),因為如果num有因子,必有一個小於等於它的算術平方根
for (int i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0) {
return 0; // 若能被5或者能被5+2整除的數,不是素數
}
}
return 1; // 其他情況是素數
}

int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);

if (is_prime(number)) {
printf("%d is a prime number.\n", number);
} else {
printf("%d is not a prime number.\n", number);
}

return 0;
}

熱點內容
壓縮油19 發布:2025-03-17 12:25:29 瀏覽:853
linux上網代理 發布:2025-03-17 12:23:56 瀏覽:356
c是高級語言嗎 發布:2025-03-17 12:16:31 瀏覽:521
python泛型 發布:2025-03-17 12:15:01 瀏覽:480
編程貓被盜 發布:2025-03-17 12:02:18 瀏覽:130
海關鎖密碼箱如何設置新密碼 發布:2025-03-17 11:53:50 瀏覽:559
農業卡號的密碼在哪裡改 發布:2025-03-17 11:48:57 瀏覽:966
楊瀾超級訪問 發布:2025-03-17 11:47:17 瀏覽:237
資料庫無損連接 發布:2025-03-17 11:47:16 瀏覽:13
memcachephp類 發布:2025-03-17 11:40:04 瀏覽:829