关于如何求素数(拭除法第五种)

该程序使用C语言实现寻找指定范围内素数的功能,采用动态内存管理来扩展数组存储素数。在找到新的素数时,会使用`realloc`调整内存大小。程序首先排除偶数并利用已知素数检查新数字,如果它是素数,则输出并保存。同时,文章讨论了`calloc`、`malloc`和`realloc`在内存分配中的应用和区别。
摘要由CSDN通过智能技术生成
#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函数的区别及用法

 加油

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值