Commit ecb9358d by Andrew Dahl

Solved Problem 20

parent 0e90a829
Showing with 66 additions and 3 deletions
Question:
n! means n (n 1) ... 3 2 1
For example, 10! = 10 9 ... 3 2 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
Answer: 648
#include <iostream>
#include <string>
#include <sstream>
#include "../include/BigInteger.h"
using namespace std;
int main() {
BigInteger sum = BigInteger("1");
BigInteger tmp = BigInteger("1");
stringstream ss;
string str;
int digit_sum = 0;
for(int i = 1; i <= 100; i++)
{
ss << i;
tmp = BigInteger(ss.str());
ss.str("");
sum *= tmp;
}
str = sum.toString();
for(int i = 0; i < str.length(); i++)
digit_sum += str[i] - '0';
cout << digit_sum << endl;
return 0;
}
......@@ -69,7 +69,7 @@ class BigInteger
if(this->value.size() == i+1)
this->value.push_back(0);
this->value[i+1] += (res / 10);
res -= 10;
res = res % 10;
}
this->value[i] = res;
}
......@@ -90,7 +90,16 @@ class BigInteger
for(int j = 0; (j < val.size()); j++)
{
res = this->value[i] * val[j];
if(values[i].size() < j+i)
if(res >= 10)
{
if(values[i].size() == j+i)
values[i].push_back(0);
if(values[i].size() == j+i+1)
values[i].push_back(0);
values[i][j+i+1] += res / 10;
res = res % 10;
}
if(values[i].size() > j+i)
values[i][i+j] += res;
else
values[i].push_back(res);
......@@ -102,8 +111,21 @@ class BigInteger
for(int i = 0; i < values.size(); i++)
{
for(int j = 0; j < values[i].size(); j++)
{
if(values[i][j] >= 10)
{
if(values[i].size() == j+1)
values[i].push_back(0);
values[i][j+1] += values[i][j] / 10;
values[i][j] = values[i][j] % 10;
}
}
for(int k = values[i].size() - 1; k >= 0; k--)
ss << values[i][k];
{
ss << values[i][k];
}
temp = BigInteger(ss.str());
ss.str("");
this->add(temp);
......
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