當前位置:首頁 » 編程語言 » 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;
}

熱點內容
贊助源碼 發布:2025-04-26 17:32:36 瀏覽:492
自助建站php源碼 發布:2025-04-26 17:32:30 瀏覽:596
千聊源碼 發布:2025-04-26 17:30:49 瀏覽:196
買單反存儲卡多大 發布:2025-04-26 17:30:01 瀏覽:724
蘋果安卓系統打碟哪個好 發布:2025-04-26 17:29:54 瀏覽:700
電腦優酷緩存電視劇如何轉mp4 發布:2025-04-26 17:29:06 瀏覽:846
sqlserverlinux 發布:2025-04-26 17:29:01 瀏覽:533
數據結構c語言描述殷人昆 發布:2025-04-26 17:24:33 瀏覽:374
安卓紅你手機隱私在哪裡開 發布:2025-04-26 17:23:33 瀏覽:417
哪些手機配置高還便宜 發布:2025-04-26 17:14:45 瀏覽:804