欧拉项目任务#8,代码在某个点之后开始返回错误的答案

Project Euler task #8, code starts returning wrong answers after certain point

本文关键字:开始 之后 返回 错误 答案 任务 项目 代码      更新时间:2023-10-16

我在一项任务中遇到了某种问题 https://projecteuler.net/problem=8,(从 1000 个数字字符串中查找 13 个连续数字的最高乘积),其中程序在某种程度上给了我可预测的结果,然后函数返回一个非常接近无符号长整形范围的数字。它发生的点取决于读取的值,例如,如果数字字符串主要由 8 和 9 组成,则它比只有 5 和 6 时发生得更快。为什么会这样?

#include <iostream>
#include <fstream>
using namespace std;

int product (int res, int a, char buffer[]){
for (int i = 0; i < a; i++){
//simple char to int conversion
res*=(buffer[i] - '0');
}
return res;
}
int main () {
char check;
int res = 1;
fstream plik;
plik.open ("8.txt");
unsigned long long int high;
unsigned long long int result;
//main function in the program
if (plik.good()){
    char buffer [13];
    for (int i = 0; i < 13; i++){
        plik >> buffer[i];
    }
    result = product (res, 13, buffer);
    high = result;
    cout << high << endl;
    //the main checking loop
    while (!plik.eof()){
    //just an interruption to make it possible to view consecutive products
    //the iteration in the buffer
    for (int i = 0; i < 12; i++){
    buffer[i] = buffer[i+1];
    }
    plik >> buffer[12];
    result = product (res, 13, buffer);
    //comparison between the current product and highest one
    if (high < result){
    high = result;
    }
    cin >> check;
    cout << high << endl;
    //again a tool for checking where the problem arises
    for (int i = 0; i < 13; i++){
        cout << buffer[i] << "  ";
    }
    cout << endl;
    }
    plik.close();
    cout << high << endl;
}
return 0;
}

程序打印出当前最高的乘积和数组中当前包含的所有数字。它看起来像这样:错误

使用 unsigned long long int 而不是 int 来计算乘积。13 位数字的乘积很容易变得大于最大的 int。