c++ - Codeforces 268B - 未知值作为此小型 C++ 程序的输出

标签 c++ integer-overflow

这是 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,而 16int,所以整个计算是用 int 完成的。

1999 * 2000 * 2001 太大 - 7,999,998,000 - int 溢出。

自始至终使用unsigned long long

关于c++ - Codeforces 268B - 未知值作为此小型 C++ 程序的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32435819/

相关文章:

c++ - 在 C++ 类的函数内部声明变量

C++,整数溢出?

ios - 声明字典 [字符串 :AnyObject] with overflowing Integers

java - 考虑边界条件的数的反转

c - 算术前限制两个变量的位位置以防止整数溢出

c - 如何处理 "((9^x)-2)%5"而不会在更高的 x 处溢出?

c++ - 如何在写入文本文件时在行中添加中断

c++ - 原子 int 不正确地递增?英特尔 TBB 实现

c++ - 传递函数作为参数

c++ - 使用 constexpr 进行基本编译时格式字符串检查