ProjectEuler prob16

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;
}

你可能感兴趣的:(ProjectEuler prob16)