问答题

【说明】
本程序用古典Eratosthenes;筛选法求从2起到指定范围内的素数。如果要找出2~10中的素数,开始时筛中有2~10的数,然后取走筛中最小的数2,宣布它是素数,并把该素数的倍数都取走。这样,第一步以后,筛子中还留下奇数3、5、7、9;重复上述步骤,再取走最小数3,宣布它为素数,并取走3的倍数,于是留下5、7。反复重复上述步骤,直到筛中为空时,工作结束,求得2~10中的全部素数。
【代码】
# include <stdio.h>
# define MAX 22500
/*程序中用数组sieve表示筛子,数组元素sieve[i]的值为1时,表示数i在筛子中,值为-1时表示数i已被取走*/
main()
unsigned int i, range, factor, k;
int sieve[MAX];
printf("please input the range:");
scanf("%d", &range);/* range 指出在多大的范围内寻找素数*/
for(i=2; i<=range; i++)
(1) ;
factor=2;
while (factor<=range)
if( (2) ) /* 筛中最小数是素数 */
printf("%d\t", factor);
k=factor;
while (k<=range) /*移走素数的倍数 */
(3) ;
k= (4) ;


(5) ;

【参考答案】

(1)sieve[i]=i
(2)sieve[factor]>0
(3)sieve[k]=-1......

(↓↓↓ 点击下方‘点击查看答案’看完整答案、解析 ↓↓↓)
热门 试题

问答题
【说明】 著名的四色定理指出任何平面区域均可以用4种颜色着色,使相邻区域着不同的颜色。本程序对给定的区域图找出所有可能的不超过4种颜色的着色方案。 【函数】 # include <stdio.h> #define N 10 *要着色的N个区域* void output(int color[]) *输出一种着色方案 color[i]的值为区域i所着颜色* int i; for (i=0; i<N; i++) printf( %4d , color[i]); printf( n ); int back(int *ip, int color[j] *回溯* int c=4; while (c==4) if (*ip<=0) return 0: --(*ip); c= (1) ; color[*ip]=-1; return c; *检查区域i,考查c种颜色的可能性 * int colorOK(iht i, int c, int adj[][N], int color[]) int j; for(j=0; j<i; j++) if ( (2) ) return 0; return 1; *为区域i选一种可着的颜色* int select(int i, int c, int adj[][N], int color[]) *寻找各种着色方案 adj[i][j]=1表示区域i与区域j不相邻* int k; for (k=c; k<=4; k++) *4种颜色* if (colorOK( (3) )) return k; return 0; int coloring(int adj[][N]) int color[N], i, c, cnt; for (i=0; i<N; i++) color[i]=-1: i=c=0; cnt=0; while (1) [ if ((c= (4) )==0) c=back(&i, color); if (c==0) return cnt; else (5) ; i++; if(i==N) output(color); ++cnt; c=back(&i, color); else c=0; void main() int adj[N][N]= 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0 ; printf( 共有%d 组解. n , coloring(adj));