实例一:输出0~~(x - 1)的平方数
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
int x;
scanf("%d", &x);
int *p = (int *)malloc(sizeof(int) * x);
/*p的理解:p是一个动态数组,长度由动态分配给出*/
for(i = 0; i < x; i++)
{
p[i] = i * i;
printf("%5d", p[i]);
}
free(p);
return 0;
}
实例二:(简化残缺版)筛法求素数
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, k;
int count;
int x;
scanf("%d", &x);
int *p = (int *)malloc(sizeof(int) * (x + 1));
p[0] = p[1] = 0;
for(i = 2; i <= x; i++)
p[i] = 1;
for(i = 2; i * i <= x; i++)
{
if(p[i] == 1)
for(k = 2; i * k <= x; k++)
p[k * i] = 0;
}
for(i = 0; (i <= x); i++)
{
if(p[i] == 1)
{
printf("%5d", i);
count++;
if(count % 10 == 0) printf("\n");
}
}
free(p);
return 0;
}