[Problem 13]欧拉
这一题的思路还是比较清晰的:
首先,由于每个数都是50位,还要计算100个这样的数的和,unsigned long long 都表示不了这么大的数,硬上肯定是不行滴;
那么,考虑到只需要打印出和值的头10位,才有了用多维数组求解的方法:
1. 首先把这100个数字保存到text文件中:这样比较好读取。
2. 把这个文件中的所有数字解析到arr[100][50]中。
3. 从最后一列开始计算一列的和,个位数(%10)进栈,剩下的(/10)作为下一列求和的进位数(基数)。每一列都这么算,直到j=0最后一列:需要把sumColumn逐位分解进栈。
4. 好,现在stack中从上到下存的就是100个数的和了。pop出top 10,就是需要的前10位数。
View Code
#include "stdafx.h"
#include <stack>
#include <fstream>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// read the num array from a txt file.
int arr[100][50];
ifstream numFile("d:\\problem13.txt");
char strNumLine[51];
int i = 0;
while(numFile.getline(strNumLine, 51))
{
int j = 0;
while(j < 50)
{
arr[i][j] = strNumLine[j] - '0';
j++;
}
i++;
}
// define a stack. kick off the sum of every column and push the last number of the sum into stack.
stack<int> numStack;
int sumColumn = 0;
for(int j = 49; j >= 0; j--)
{
for(int i = 0; i <= 99; i++)
{
sumColumn += arr[i][j];
}
if(j != 0)
{
numStack.push(sumColumn%10);
sumColumn = sumColumn / 10;
}
else
{
while(sumColumn > 1)
{
numStack.push(sumColumn%10);
sumColumn /= 10;
}
}
}
// pop up the last ten number in stack. They are the top ten number of the whole sum.
i = 1;
while(i <= 10)
{
cout << numStack.top() << endl;
numStack.pop();
i++;
}
return 0;
}
#include <stack>
#include <fstream>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// read the num array from a txt file.
int arr[100][50];
ifstream numFile("d:\\problem13.txt");
char strNumLine[51];
int i = 0;
while(numFile.getline(strNumLine, 51))
{
int j = 0;
while(j < 50)
{
arr[i][j] = strNumLine[j] - '0';
j++;
}
i++;
}
// define a stack. kick off the sum of every column and push the last number of the sum into stack.
stack<int> numStack;
int sumColumn = 0;
for(int j = 49; j >= 0; j--)
{
for(int i = 0; i <= 99; i++)
{
sumColumn += arr[i][j];
}
if(j != 0)
{
numStack.push(sumColumn%10);
sumColumn = sumColumn / 10;
}
else
{
while(sumColumn > 1)
{
numStack.push(sumColumn%10);
sumColumn /= 10;
}
}
}
// pop up the last ten number in stack. They are the top ten number of the whole sum.
i = 1;
while(i <= 10)
{
cout << numStack.top() << endl;
numStack.pop();
i++;
}
return 0;
}