3-1 以2为底N的对数,向上取整
#include <stdio.h>
int lg(int N) //以2为底N的对数,向上取整
{
int i;
for (i = 0; N > 0; i++, N /= 2) ;
return i;
}
main()
{
int i, N;
for (i = 1, N = 10; i <= 6; i++, N *= 10)
printf("%7d %2d %9d\n", N, lg(N), N*lg(N));
}
3-2 估计rand()函数的分布参数
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
main(int argc, char *argv[])
{
int i, N = 10000;
float m1 = 0.0, m2 = 0.0;
int x;
for (i = 0; i < N; i++)
{
x = rand();
m1 += ((float) x)/N;
m2 += ((float) x*x)/N;
}
printf(" Average: %f\n", m1); //RAND_MAX/2 = 16383.5 均值
printf("Std. deviation: %f\n", sqrt(m2-m1*m1)); //标准差
}
3-5 筛子法输出小于N的质数
#define N 10000
main()
{
int i, j, a[N];
for (i = 2; i < N; i++)
a[i] = 1;
for (i = 2; i < N; i++)
for (j = i; j < N/i; j++)
a[i*j] = 0;
for (i = 2; i < N; i++)
if (a[i])
printf("%4d ", i);
printf("\n");
}
3-7 模拟正态分布
#include <stdlib.h>
#define M 8000 //试验次数
#define N 100 //分布范围 0~N
int heads()
{
return rand() < RAND_MAX/2; //等概率发生器
}
main(int argc, char *argv[])
{
int i, j, cnt;
int *f = malloc((N+1)*sizeof(int)); //统计表
for (j = 0; j <= N; j++)
f[j] = 0;
for (i = 0; i < M; i++, f[cnt]++) //进行M次的试验
for (cnt = 0, j = 0; j <= N; j++) //cnt为以N/2为期望的正态分布的随机变量(0~N)
if (heads())
cnt++;
for (j = 0; j <= N; j++)
{
printf("%2d ", j);
for (i = 0; i < f[j]; i+=10) //出现10次,给一个星星
printf("*");
printf("\n");
}
}
3.9 链环 约瑟夫环
//约瑟夫环(链环) 共N个人 每隔M个人挑出一个
#include <stdlib.h>
typedef struct node* link;
struct node {
int item;
link next;
};
main( )
{
int i,N = 10,M = 3;
link t = malloc(sizeof *t), x = t; t->item = 1; t->next = t;
for (i = 2; i <= N; i++)
{
x = x->next = malloc(sizeof *x);
x->item = i;
x->next = t ; //首位相连
}
while (x != x->next)
{
for (i = 1; i < M; i++)
x = x->next; //定位到x后的第M-1个
x->next = x->next->next; //删除第M个(没有进行内存释放,有问题)
printf("%d\n", x->item);
N--;
}
}