/*************************************************************************************
*file: Prime.c
*data: 2013/3/10
*description:
(1)2是最小的素數,且是唯一的偶素數,故單獨列出
(2-被除數)偶數必然能夠被2整除,因此被除數只判斷奇數(2單獨處理)
(3-除數)由於被除數限制在奇數的範圍內,故不可能被2整除,因此除數從3開始遍歷。
除數的遍歷從3開始,到sqrt(x)結束。因數都是成對出現的。比如,100的因
數有:1和100,2和50,4和25,5和20,10和10。成對的因數,其中一個必然
小於等於100的開平方,另一個大於等於100的開平方。
**************************************************************************************/
#include <stdio.h>
#include <math.h>
#include <windows.h>
#define DATA_SIZE 10000 //測試DATA_SIZE以內的素數
#define BOOL unsigned char
#define true 1
#define false 0
BOOL IsPrime(int x);
int main()
{
int data; //被測試的數
int count; //素數的個數
DWORD time_head; //程序開始時間
time_head = GetTickCount(); //獲取程序開始執行時的時間
printf("************************ P r i m e ************************\n");
printf("%5d",2); //由於2是最小的素數,且是唯一的偶素數,故單獨列出
//由於偶數不會是素數,故只遍歷DATA_SIZE內的奇數
for(data = 3,count = 1;data <= DATA_SIZE;)
{
if(IsPrime(data) == true) //判斷data是否爲素數
{
printf("%5d",data);
count++;
if((count % 8) == 0) //每輸出8個素數,換行,控制格式
{
printf("\n");
}
}
data += 2; //修正被測數值
}
printf("\n\nThe total number of prime is %d",count);
//打印程序運行時間,精確到毫秒
printf("\nThe running time of program is %ld ms\n",GetTickCount() - time_head);
printf("\n************************ O V E R ************************\n");
return 0;
}
/*
*判斷參數x是否爲素數
*x是素數返回true
*x不是素數返回false
*/
BOOL IsPrime(int x)
{
int div;
if(x < 2)
{
return false;
}
else if(x == 2) //2是最小的素數,也是唯一的偶數素數
{
return true;
}
//由於只判斷奇數,故不可能被2整除,i從3開始的奇數算起
for(div = 3;div <= sqrt(x);div += 2) //!!!參數i必須<=sqrt(x)!!!
{
if((x % div) == 0)
{
return false;
}
}
return true;
}
素數的查找
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.