程序说明
程序接受两个正整数的输入,构成一个闭区间,找出这个区间内的所有质数。
算法说明
判断一个数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;
}
运行结果
注
在Linux下编译时,若出现undefined reference to `sqrt’的错误,则编译时还需要使用-lm
连接到数学函数库
cc prime.c -lm