What's wrong in my code for REMOVEMUL problem

My issue

I got the right idea of how to solve this problem. Why did i get WA during the contest?

My code

#include <bits/stdc++.h>
using namespace std;

void solve() {
    int t;
    cin >> t;
    while(t--) {
        int n, m;
        cin >> n >> m;
        int arr[m];
        long long int sumM = 0;
        for(int i = 0; i < m; i++) {
            cin >> arr[i];
            sumM += arr[i];
        long long int sumN = n*(n+1) / 2;

        cout << sumN - sumM << endl;

int main() {

    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);

    return 0;

Problem Link: REMOVEMUL Problem - CodeChef

In the line:

long long int sumN = n*(n+1) / 2;

the left side of the expression is long long int. On the right side, n is an int. So, n + 1 is also an int. Then n * (n+1) (int * int) will also has to be an int, which in some cases would exceed the int datatype capacity. This would result in a strange value, which would still be int. Only after diving by 2 (int), it would implicilty convert to long long int datatype.

To resolve this, just use-

long long int sumN = n*(n+1LL) / 2;

This would make the calculations stick to long long.

1 Like

Thank you so much, bro. I understand now. It was a silly mistake. :sweat_smile:

1 Like