这是 Codeforces problem 的 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
作为输出,但事实并非如此。代码有什么问题?
最佳答案
当您执行算术运算时,如果结果太大,则不会将其提升为更宽的类型。
因为 n
是一个 int
,而 1
和 6
是 int
,所以整个计算是用 int
完成的。
1999 * 2000 * 2001 太大 - 7,999,998,000 - int
溢出。
自始至终使用unsigned long long
。
关于c++ - Codeforces 268B - 未知值作为此小型 C++ 程序的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32435819/