Project Euler | Problem 016

Problem 16


Power digit sum

2 ^ 15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2 ^ 1000?


幂的数字和

2 ^ 15 = 32768,而 32768的各位数字之和是 3 + 2 + 7 + 6 + 8 = 26。

2 ^ 1000的各位数字之和是多少?


/*
*	Program 1
* 思路:
*	1.没能找到一个合理的函数解决此问题,只能采取暴力计算的方式
*	2.明显数字 2 ^ 1000过大,运用数组进行储存
* 收获:
*	1.1.过大数字运用数组储存
*	1.2.结构体表征一个动态数组
*	1.3.再次开辟空间的初始化
* 评价:
*	优点:
*		1.结构体参与管理数组,方便数据的储存和修改
*	缺点:
*		1.没能找到一个简洁明了的函数解决该问题
*		2.对再次开辟空间的初始化显得很拙略,不能解决跟多情况
*/

#define _CRT_SECURE_NO_WARNINGS
#define UP_LIMIT 1000
#define NUM      2
#define INIT_CAPACITY 1
#define INIT_SIZE     2

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct Power_t // 收获1.1 - 1.2
{
	int* data;    //倒序储存幂的结果
	int capacity; //幂的位数
	int size;     //数组 data的大小
}Power_t;

//初始化结构体 Power_t
void InitPower_t(Power_t* power);
//维护结构体 Power_t中数组 data的大小总比所储存的幂的位数 capacity多 1
void CheckCapacity(Power_t* power);
//销毁因结构体 Power_t而开辟的堆空间
void DestroyPower_t(Power_t* power);

/*------------------------------------------------------------------------*/

int main()
{
	Power_t power;
	InitPower_t(&power);
	for (int index = 0; index < UP_LIMIT; index++)
	{
		CheckCapacity(&power);
		//逐位乘法
		for (int i = 0; i < power.capacity; i++)
		{
			power.data[i] *= NUM;
		}
		//进位		
		for (int i = 0; i < power.capacity; i++)
		{
			if (power.data[i] > 9)
			{
				power.data[i + 1] += power.data[i] / 10;
				power.data[i] %= 10;
			}
		}
		if (power.data[power.capacity] != 0)
		{
			power.capacity++;
		}
	}

	//打印
	int ret = 0;
	for(int i = 0; i < power.capacity; i++)
	{
		ret += power.data[i];
	}
	printf("%d\n", ret);

	DestroyPower_t(&power);
	return 0;
}

/*------------------------------------------------------------------------*/

void InitPower_t(Power_t* power)
{
	assert(power);

	int* pf = (int*)calloc(INIT_SIZE, sizeof(int));
	if (pf == NULL)
	{
		perror("InitPower_t");
	}
	power->data = pf;
	pf = NULL;

	power->data[0] = 1;// 2 ^ 0 = 1
	power->capacity = INIT_CAPACITY;
	power->size = INIT_SIZE;
}

void CheckCapacity(Power_t* power)
{
	assert(power);

	if (power->size != power->capacity + 1)
	{
		int* pf = (int*)realloc(power->data, (power->capacity + 1) * sizeof(int));
		if (pf == NULL)
		{
			perror("CheckCapacity");
		}
		power->data = pf;
		pf = NULL;
	}

	power->data[power->capacity] = 0;//将新开辟的空间置零 // 收获1.3
	power->size = power->capacity + 1;
}

void DestroyPower_t(Power_t* power)
{
	assert(power);

	free(power->data);
	power->data = NULL;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值