判斷是否爲質數

程序說明

程序接受兩個正整數的輸入,構成一個閉區間,找出這個區間內的所有質數。

算法說明

判斷一個數n是否爲質數時,先對這個數開平方,隨後從2開始,循環到這個平行根,檢查其中的數能否整除數n,若能整除,則爲合數,否則爲質數。由於sqrt函數的返回值是double類型,爲保證準確性(如sqrt(4)返回值可能是1.9999999),循環的取值區間應爲[2, sqrt(n)+1)。

程序代碼

/* 
 * prime.c
 * Output all prime numbers in a range.
 * writen by Liangjin Song on 20191030
*/
#include <stdio.h>
#include <math.h>

#define uint    unsigned int
#define Bool    int
#define True    1
#define False   0

Bool is_prime(uint number)
{
    for(uint i=2; i< sqrt(number)+1; ++i){
        if(number%i==0){
            return False;
        }
    }
    return True;
}

int main()
{
    uint a,b;
    do{
        printf("Please input two positive integers a and b (2 <= a < 10, b < 1000):\n");
        scanf("%d%d",&a,&b);
    }while(!(a < 10 && a>=2 && b < 10000));
    
    printf("The prime numbers in the range [%d, %d]:\n",a,b);
    for(uint n=a; n<=b; ++n){
        if(is_prime(n)){
            printf("%d  ",n);
        }
    }
    printf("\n");
    return 0;
}

運行結果

2-100之間的質數

在Linux下編譯時,若出現undefined reference to `sqrt’的錯誤,則編譯時還需要使用-lm連接到數學函數庫

cc prime.c -lm
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章