Codeforces 268B -未知值作为这个小c++程序的输出

Codeforces 268B - Unknown value as output for this small C++ program

本文关键字:c++ 程序 输出 268B 未知 Codeforces      更新时间:2023-10-16

下面是我试图解决的Codeforces问题的c++代码:

#include <iostream>
using namespace std;
int main()
{
    int n = -1;
    unsigned long long possible_combinations = 0;
    cin >> n;
    possible_combinations = (((n - 1) * n * (n + 1)) / 6) + n;
    cout << possible_combinations;
    return 0;
}

其中1 <= n <= 2000 .

对于n的小值它计算正确的值,但是当我使用2000时,它显示- 18446744073611230851。我只尝试了几个测试用例。

我知道公式是正确的,程序应该输出1333335000,但它没有。代码有什么问题?

当您执行算术运算时,如果结果变得太大,则不会提升为更宽的类型。
由于nint, 16int,所以整个计算都是用int完成的。

1999 * 2000 * 2001是如此之大—7,999,998,000—以至于int溢出。

始终使用unsigned long long

试试这个:

possible_combinations = (((unsigned long long) (n - 1) * n * (n + 1)) / 6) + n;

问题的原因很简单:如果n==2000, (n - 1) * n * (n + 1)对于int来说太大(但是您的nint,因此此表达式返回int)。因此,您可以要求编译器使用更大的类型(语言不能自动使类型更宽)或只是更改n的类型(使用unsigned long longn = -1;而不是int n = -1;)。