You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

给定数组找和可被7整除的数对:编写的C++代码未通过全部测试

Fixing Your Code to Find Pairs Whose Sum is Divisible by 7

Let's break down why your code isn't passing all test cases and fix it up!

The Core Problem: Negative Remainders in C++

In C++, when you take the modulus of a negative number, the result is negative. For example, -1 % 7 returns -1 instead of the mathematically correct remainder 6 (since -1 = 7*(-1) + 6).

This causes two big issues in your code:

  • You're accessing the array m with negative indices (like m[-1]), which is undefined behavior—this can crash your program or give wrong results.
  • The remainder value you're using doesn't match the actual remainder we need for counting valid pairs, so your pair count will be incorrect for test cases with negative numbers.

The Fix: Normalize Remainders to Non-Negative Values

Instead of just doing a %= 7;, adjust the remainder to ensure it's always in the range 0 to 6 using this line:

a = (a % 7 + 7) % 7;

Adding 7 ensures the value is positive before taking modulus again, so even if a % 7 is negative, we get the correct non-negative remainder.

Corrected Full Code

Here's your updated code with this fix:

#include <iostream>
using namespace std;

int m[7]; // Global arrays are initialized to 0 by default, which is perfect for us

int main() {
    int n, k = 0;
    cin >> n;
    long long a;
    
    for(int i = 0; i < n; i++) {
        cin >> a;
        a = (a % 7 + 7) % 7; // Normalize remainder to 0-6
        if(m[(7 - a) % 7] > 0) {
            k += m[(7 - a) % 7];
        }
        m[a]++;
    }
    
    cout << k;
    return 0;
}

Why This Works

  • For positive numbers: (a %7 +7)%7 is the same as a%7, so no change to your original logic for positive inputs.
  • For negative numbers: We convert the negative remainder to its equivalent positive one (e.g., -1 becomes 6, -2 becomes 5, etc.), so we count pairs correctly (since a number with remainder 6 pairs with a number with remainder 1 to make a sum divisible by 7, just like positive 6 and 1 do).
  • The rest of your logic for counting pairs is solid—you're tracking how many times each remainder has appeared, and adding the count of complementary remainders whenever a new number is processed.

内容的提问来源于stack exchange,提问作者AHMAD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:51:39