0

Given two sets of integers P and C of the same length. How can I find ALL matching sums of consecutive elements at the same starting and ending positions in the two sets, including overlapping subsets?

C# is preferred but non-Linq please.

Example:

Let P and C be the sets of the first ten prime and composite numbers:
P = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }
C = { 4, 6, 8, 9, 10, 12, 14, 15, 16, 18 }

Match 1: [index starts at 0]
SumP[3..5] = 7 + 11 + 13 = 31
SumC[3..5] = 9 + 10 + 12 = 31

Match 2: [index starts at 0]
SumP[2, 6] = 5 + 7 + 11 + 13 + 17 = 53
SumC[2, 6] = 8 + 9 + 10 + 12 + 14 = 53

I need to find if the above two sums are the only ones or not!

4
  • 1
    "at the same starting and ending positions in the two sets" Cool, gotcha. "including overlapping subsets?" Overlapping. What? If they have the same start and end positions, what is overlapping what? Can you explain that aspect in more detail with an example? Commented Apr 5, 2022 at 20:07
  • 1
    At first glance this is just a set of brute force nested for loops generating all the possible start/end positions. Commented Apr 5, 2022 at 20:09
  • 1
    Probably also at second glance, since this is inherently a quadratic problem (if we don't try to get fancy with exploiting properties of primes and composites and just assume arbitrary lists). Hint: for (int i = 0; i < P.Length; ++i) { int sum_P = P[i]; int sum_C = C[i]; for (int j = 1; j < P.Length - i; ++j) { ...} }. Commented Apr 5, 2022 at 20:16
  • Overlapping matching subsets can either be nested as in the given example or their starting index is before the ending index of the previous matching two subsets. Commented Apr 5, 2022 at 20:18

1 Answer 1

1

Here's the brute force approach with nested for loops, ignoring the "overlapping" part which I don't understand yet:

for(int indexA=0; indexA<P.Length; indexA++) {
  for(int indexB=indexA; indexB<P.Length; indexB++) {
    int sumA = 0, sumB = 0;
    for(int i=indexA; i<=indexB; i++) {
      sumA += P[i];
      sumB += C[i];
    }
    if (sumA == sumB) {
      Console.WriteLine("[" + indexA + ", " + indexB + "] : Sum = " + sumA);
    }
  }
}

Output:

[2, 6] : Sum = 53
[3, 5] : Sum = 31
Sign up to request clarification or add additional context in comments.

2 Comments

Too slow for a 10,000 numbers.Any optimization please as I need to do it for 1000000 primes and composites. Perhaps there are no more than these two matching subsets (53 and 31) because prime numbers increase much fasters than composite numbers.
You will love these twin numbers 😊 QuranCode.com/506Paper.pdf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.