kainster

never too late
posts - 33, comments - 3, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

ProjectEuler prob16

Posted on 2008-10-06 19:53 kainster 阅读(187) 评论(1)  编辑  收藏

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?

也可以用matlab或者Mathematica之类的直接计算2的一千次方,然后把结果的各位相加即可
但是用C或者C#的话需要自己实现大整数类,和大整数的乘法(乘法其实是很多次的加法)
#include<iostream>
#include<stdlib.h>
#include<vector>
#include<string>
#include<math.h>
using namespace std;
typedef vector<int> intvec;
class number;
/*
function to multiply a given number by 2 n times
*/
number multiply2(number bas,int Ntimes);
/*
function to calculate sum of digits of a number
*/
int SumDigit(number digits);
/*
class number which can accommodate very large unsigned integers
have an operator to add two numbers of same length
(can be easily modified to add numbers of unequal length )
*/
class number
{
public:
friend number multiply2(number bas,int Ntimes);
friend int SumDigit(number digits);
number(string strval);
number();
number operator +(number sec);
void display();
private:
intvec value;
};

main()
{
number two("2");
number result;
int sum2pow1000;
result=multiply2(two,1000);
sum2pow1000=SumDigit(result);
cout<<"2^1000 : ";
result.display();
cout<<endl;
cout<<"sum of the digits of the number 2^1000 : "<<sum2pow1000;
return 0;

}
number::number(string strval)
{
string::iterator pos;
value.clear();
int insert;
for(pos=strval.end()-1;pos!=strval.begin()-1;pos--)
{
insert=pos[0]-'0';
value.push_back(insert);
}
}
number::number()
{
value.clear();
}

number number::operator +(number sec)
{
int limit,carry=0;
number result;
limit=sec.value.size();
if(limit>value.size())
limit=value.size();
for(int i=0;i<limit;i++)
{
carry=sec.value+value+carry;
result.value.push_back(carry%10);
carry=carry/10;
}
if(carry)
result.value.push_back(carry%10);
return result;
}

void number::display()
{
intvec::iterator pos;
for(pos=value.end()-1;pos!=value.begin()-1;pos--)
cout<<pos[0];
}
number multiply2(number bas,int Ntimes)
{
for (int i=1;i<Ntimes;i++)
{
bas=bas+bas;
}
return bas;
}
int SumDigit(number digits)
{
int sum=0;
intvec::iterator pos;
for(pos=digits.value.end()-1;pos!=digits.value.begin()-1;pos--)
sum=sum+pos[0];
return sum;
}


评论

# re: ProjectEuler prob16  回复  更多评论   

2009-03-10 13:29 by projecteuler
mathematica code:

Plus @@ IntegerDigits[2^1000]

只有注册用户登录后才能发表评论。


网站导航: