1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//存取所需函式
#include <stdio.h>
#include <math.h>
 
//主程式
int main(void){
 
    //定義變數
    int test,input,checked;
    float input_sqrt;
 
    printf("這支程式用來檢測一個數字是否為質數,可輸入-1來退出程式\n\n");
    while(1){
        printf("要檢查的數字:");
        scanf_s("%d", &input);
        if(input == EOF)
            break;
 
        if(input == 2){
            printf("結果:質數\n\n");
        }else if((input % 2) == 0){
                printf("結果:非質數,最小因數為2\n\n");
        }else{
            checked = 0;
            input_sqrt = sqrt((float)input);
            for(test = 3; test <= input_sqrt; test += 2){
                if((input % test) == 0){
                    printf("結果:非質數,最小因數為%d\n\n", test);
                    checked = 1;
                    break;
                }
            }
            if(checked != 1)
            printf("結果:質數\n\n");
            }
    }
    return 0;
}