[Project Euler] 来做欧拉项目练习题吧: 题目016

                                               [Project Euler] 来做欧拉项目练习题吧: 题目016

                                                                       周银辉 

 

问题描述

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

What is the sum of the digits of the number 21000? 

 

问题分析:

直接用大数乘法就可以解决,并且速度挺快(言下之意"所以没有去找其他的招了").

将数字转换成字符串进行处理,2^m = 2^(m-1) * 2 我们将2^(m-1)放在字符数组buffer中,与2相乘时进位放在字符数组temp中,然后就可以模拟乘法了。 

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

 

#define POWER  1000
#define BUF_SZ 310

 

int test(char *buffer, char *temp)
{
buffer[BUF_SZ-1] = '2';
int i, j, a, b, c;

 

for(i=2; i<=POWER; i++)
{
for(j=BUF_SZ-1; j>=0; j--)
{
a = (int)buffer[j]-48;
b = (int)temp[j]-48;
c = a*2+b;

 

buffer[j] = (char)(c%10+48);

 

if(j>0)
{
temp[j-1] = (char)(c/10+48);
}
}
}

 

int result=0;
for(i=0; i<BUF_SZ; i++)
{
result += (int)buffer[i]-48;
}

 

return result;
}

 

int main()
{
char *buffer = (char*)malloc(sizeof(char)*BUF_SZ);
char *temp   = (char*)malloc(sizeof(char)*BUF_SZ);

 

memset(buffer, '0', BUF_SZ);
memset(temp,   '0', BUF_SZ);

 

printf("sum is: %d\n", test(buffer,temp));
printf("buffer is: %s\n", buffer);
free(buffer);
free(temp);

 

return 0;
}

 

BUF_SZ之所以取310,因为我偷偷用计算器算了下2^1000的数量级是301,呵呵

 

在我的机器上(intel 2.4G双核):

real    0m0.011s

user    0m0.007s

sys     0m0.003s 

 

posted @ 2011-02-25 21:15  周银辉  阅读(2100)  评论(0编辑  收藏  举报