1. 程式人生 > >C語言之判斷一個數是否為素數

C語言之判斷一個數是否為素數

#include "stdio.h"
#include"time.h"
#include"math.h"

int isPrimeNumber(int number) { //判斷是否為素數
    float sqrtOfNum = sqrt((double) number);
    for (int j = 2; j <= sqrtOfNum; j++) //從2到number的算術平方根迭代
        if (number / j * j == number) //判斷j是否為number的因數
            return 0;
    return 1;
}

void printNum(int number) { //打印出 <= number的所有質數
    int j = 0;
    for (int i = 2; i <= number; i++)
        if (isPrimeNumber(i) == 1) {
            printf("%-10d", i);
            j++;
            if (j % 10 == 0) //每隔十個數字換行
                printf("\n");
        }
}

int main() {
    long start = time(NULL);
    printf("%d\n", isPrimeNumber(29));
    printNum(100);
    printf("\n");
    long end = time(NULL);
    printf("Time spent: %d", end - start);
}

執行結果:

1
2         3         5         7         11        13        17        19        23        29        
31        37        41        43        47        53        59        61        67        71        
73        79        83        89        97        
Time spent: 0