#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define LEN 10
int main()
{
int m = 0, n = 0;
int sushu(int m, int n);
printf("求m和n之间的素数\n");
printf("请输入m和n的值:");
scanf("%d%d", &m, &n);
system("cls");
sushu(m, n);
return 0;
}
int sushu(int m, int n)
{
int i = 0, x= 0;
int k = 1;
int* arr = (int*)calloc(sizeof(int), LEN);
int count = 0,cost = 1;
if (arr == NULL)
{
printf("out of memory");
exit(EXIT_FAILURE);
}
if (m % 2 == 0)//从奇数开始
m = m + 1;
if (m >= 2)//给第一个arr赋值
{
arr[0] = 2;
}
for (i = 3; i <= n; i += 2)//求新的素数
{
x = 0;
while (arr[x] > 0 && arr[x] <= sqrt(i))
{
if (i % arr[x] == 0)
{
break;
}
x++;
}
if (arr[x] == 0 || arr[x] > sqrt(i))//输出素数并且保存一部分
{
if (i >= m)
{
printf("%d\n", i);
cost++;
}
if (x >= count * LEN)//增加arr的内存
{
count++;
if (arr != NULL)
{
int* y = (int*)realloc(arr, LEN * sizeof(int) * count);
if (y == NULL)
{
printf("out of memory");
exit(EXIT_FAILURE);
}
else
{
arr = y;
}
}
}
arr[k] = i;
k++;
}
}
printf("总数为:%d", cost);
free(arr);
arr = NULL;
return 0;
}
http://t.csdn.cn/3zLLKhttps://blog.csdn.net/rain67/article/details/115100474
这个是关于动态内存管理的文章,calloc、malloc、realloc函数的区别及用法
加油