[Problem 13]歐拉

來源:互聯網
上載者:User

這一題的思路還是比較清晰的:

首先,由於每個數都是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;
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.