Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int Source[]; // The initial array.
- // First, we calculate the difference between the sum of all the elements of the array and the sum of the integers from 1 to N.
- int sum_ref = 0;
- int sum_source = 0;
- int index = 0;
- foreach (int i in Source)
- {
- sum_ref += ++index;
- sum_source += i;
- }
- int diff = abs(sum_source - sum_ref);
- // Now we build two sums : Sum1 (resp. Sum2) is the sum of all the integers which euclidean division by diff is even (resp. odd).
- // (Once again, ref is for integers 1 to N and source is for the Array)
- int sum1_ref = 0;
- int sum1_source = 0;
- int sum2_ref = 0;
- int sum2_source = 0;
- index = 0;
- foreach (int i in Source)
- {
- index++;
- if (isEven(div(index, diff)))
- sum1_ref += index
- else
- sum2_ref += index;
- if (isEven(div(i, diff)))
- sum1_source += i
- else
- sum2_source += i;
- }
- // Finally, the positive difference between ref and source is the missing number, and the negative one is the duplicate.
- int duplicate, missing;
- if (sum1_ref > sum1_source)
- {
- missing = sum1_ref - sum1_source;
- duplicate = sum2_source - sum2_ref;
- }
- else
- {
- missing = sum2_ref - sum2_source;
- duplicate = sum1_source - sum1_ref;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement