给定数组找和可被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
mwith negative indices (likem[-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)%7is the same asa%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.,
-1becomes6,-2becomes5, etc.), so we count pairs correctly (since a number with remainder6pairs with a number with remainder1to 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
相关产品推荐
相关产品推荐

