首页 > 代码库 > 小算法笔记

小算法笔记

素数: 除 1 外只能被 1 和自身整除的数。

方法一:

#include <stdio.h>#define N 1000int num = 0;int prime(int n){	int i;	if(n % 2 == 0)		return (n == 2);	if(n % 3 == 0)		return (n == 3);	if(n % 5 == 0)		return (n == 5);	for(i = 7; i*i <= n; ++i)		if(n % i == 0)			return 0;	return 1;}void main(){	int i;	for(i = 2; i < N; ++i)		if(prime(i))			printf("%-4d %d\n", ++num, i);}

 

方法二(筛选法):

#include <stdio.h>#include <math.h>#include <time.h>#define N 1000bool tag[N+1] = {0};int num = 0;int prime(int n){	int i;	if(n % 2 == 0)		return (n == 2);	if(n % 3 == 0)		return (n == 3);	if(n % 5 == 0)		return (n == 5);	for(i = 7; i*i <= n; i += 2)		if(n % i == 0)			return 0;	return 1;}void main(){	clock_t tic;	tic = clock();	int i, v, bound;	bound = (int)sqrt((float)N);	for(i = 2; i <= bound; ++i)	{		if(!prime(i))  tag[i] = 1;		if(!tag[i]){			v = i + i;			while(v <= N){				tag[v] = 1;				v += i;			}		}	}	for(i = 2; i <= N; ++i)		if(!tag[i])			printf("%-4d %d\n", ++num, i);	printf("%d ms\n", clock()-tic);}