Commit b8bafd19 by Andrew Dahl

Solved Problem 16

parent b1c19607
Showing with 156 additions and 0 deletions
Question:
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?
Answer: 1366
#include <iostream>
#include <sstream>
#include <string>
#include <math.h>
#include "../include/BigInteger.h"
using namespace std;
int main() {
BigInteger temp = BigInteger("2");
BigInteger temp2 = BigInteger("2");
string str;
int sum = 0;
for(int i = 1; i < 1000; i++)
temp*=temp2;
str = temp.toString();
for(int i = 0; i < str.size(); i++)
sum += str[i] - '0';
cout << sum << endl;
return 0;
}
#include <string>
#include <sstream>
#include <vector>
using namespace std;
class BigInteger
{
public:
BigInteger(string num)
{
this->value = toVector(num);
}
const BigInteger operator*(const BigInteger &rhs) const
{
BigInteger newInt = *this;
newInt += rhs;
return newInt;
}
BigInteger & operator*=(const BigInteger &rhs)
{
this->mul(rhs);
return *this;
}
const BigInteger operator+(const BigInteger &rhs) const
{
BigInteger newInt = *this;
newInt += rhs;
return newInt;
}
BigInteger & operator+=(const BigInteger &rhs)
{
this->add(rhs);
return *this;
}
BigInteger & operator=(const BigInteger &rhs)
{
this->value = rhs.value;
return *this;
}
string toString()
{
stringstream ss;
for(int i = this->value.size() - 1; i >= 0; i--)
ss << value[i];
return ss.str();
}
private:
void add(BigInteger rhs)
{
vector<int> val = toVector(rhs.toString());
int res = 0;
for(int i = 0; (i < this->value.size()) || (i < val.size()); i++)
{
if(val.size() == i)
val.push_back(0);
if(this->value.size() == i)
this->value.push_back(0);
res = this->value[i] + val[i];
if(res >= 10)
{
if(this->value.size() == i+1)
this->value.push_back(0);
this->value[i+1] += (res / 10);
res -= 10;
}
this->value[i] = res;
}
}
void mul(BigInteger rhs)
{
BigInteger temp = BigInteger("0");
stringstream ss;
vector<int> val = toVector(rhs.toString());
vector<vector<int> > values;
int res = 0;
for(int i = 0; (i < this->value.size()); i++)
{
values.push_back(vector<int>());
for(int k = 0; k < i; k++)
values[i].push_back(0);
for(int j = 0; (j < val.size()); j++)
{
res = this->value[i] * val[j];
if(values[i].size() < j+i)
values[i][i+j] += res;
else
values[i].push_back(res);
}
}
this->value.clear();
for(int i = 0; i < values.size(); i++)
{
for(int k = values[i].size() - 1; k >= 0; k--)
ss << values[i][k];
temp = BigInteger(ss.str());
ss.str("");
this->add(temp);
}
}
vector<int> toVector(string num)
{
vector<int> val;
for(int i = num.size() - 1; i >= 0; i--)
val.push_back(num[i] - '0');
return val;
}
vector<int> value;
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment