小程序_素数

题目:求100之内的素数 
1. 程序分析:判断素数的方法:用一个数分别去除2sqrt(这个数),如果能被整除, 则表明此数不是素数,反之是素数

#include <stdio.h>
#include <math.h>

int primeNum(void); /* 求素数 */
int primeNumInRange(void); /* 求Range以内素数 */


void main(void)
{
printf("Hello world\n");
//primeNum();
primeNumInRange();
}

 

/* Prime numbers can only be divided by one or itself*/
int primeNum(void)
{
int count = 0;
int result = 1; //default value is primeNum
int testObject;

printf("Pls input test num:");
scanf("%d",&testObject);

for(count=2; count < testObject/2 ; count++)
{
if(0 == testObject%count)
{
result = 0;
printf("It is not a prime Num, it can be divided by %d \n",count);
break;
}
}

if(1 == result)
{
printf("Prime number, It can only be divided by one or itself \n");
}

return result;
}

/* Prime numbers in 100 can only be divided by one or itself*/
int primeNumInRange(void)
{
#define MIN_NUM 1
#define MAX_NUM 255
int count = 0;
int result = 1; //default value is primeNum
int num;
int totalcount = 0;


for(num = MIN_NUM ; num < MAX_NUM+1 ;num++)
{
result = 1;
for(count = 2; count < sqrt(num+1) ; count++)
{
if(0 == num%count)
{
result = 0;
break;
}
}

if(1 == result)
{
totalcount++;
printf("%4d ",num);
if(0 == totalcount%5)
{
printf("\n");
}
}
}

printf("\nTotal prime number is [%d]\n", totalcount);
return result;
}

 

posted @ 2016-08-25 10:17  H_amy  阅读(252)  评论(0编辑  收藏  举报