I recently saw a nice solution to a programming problem. Given 2 lists, find the missing number in one of the lists.
My initial solution was like this:
long long missing_2(long long a[], long long b[], long long bsize) {
long long asum = a[bsize], bsum = 0;
for (long long i = 0; i < bsize; i++) {
asum += a[i];
bsum += b[i];
}
return asum-bsum;
}
but someone suggested something like this:
long long missing_3(long long a[], long long b[], long long bsize) {
long long sum = 0 ^ a[bsize];
for (long long i = 0; i < bsize; i++) {
sum ^= a[i];
sum ^= b[i];
}
return sum;
}
out of curiosity, I timed the 2 solutions thinking that the second one missing_3
would be faster. I got these results
missing_2: Time taken: 16.21s
missing_3: Time taken: 23.39s
The lists are generated using a for-loop. List b is filled with ints 0-1000000000
and list a is filled 1-1000000000 with a random number appended at the end (so that it contains 1 different (extra) value.
Question The bitwise version takes 23.39s, the summation version takes 16.21s. Any idea why the bitwise version would be noticeably slower than the summation version? I would have assumed bitwise operations would be faster than addition or at least similar.
Edit:
compiled using g++
with no extra flag/options.
Edit2:
Tested with flags -O1
and -O2
, no noticeable difference.
Edit3:
Here is the driver code:
long long smaller_size = 1000000000;
long long* a = new long long[smaller_size+1];
long long* b = new long long[smaller_size];
for(long long i = 0; i < smaller_size; i++){
a[i] = b[i] = i;
}
a[smaller_size] = 1434;
// std::cout << missing_1(a, b, smaller_size) << std::endl;
clock_t tStart = clock();
std::cout << "Start List Test\n";
std::cout << missing_2(a, b, smaller_size) << std::endl;
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
tStart = clock();
std::cout << missing_3(a, b, smaller_size) << std::endl;
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
Edit 5: Timing section updated (No time change)
clock_t tStart = clock();
std::cout << "Start List Test\n";
double time;
missing_2(a, b, smaller_size);
time = (double)(clock() - tStart)/CLOCKS_PER_SEC;
printf("Time taken: %.2fs\n", time);
tStart = clock();
missing_3(a, b, smaller_size);
time = (double)(clock() - tStart)/CLOCKS_PER_SEC;
printf("Time taken: %.2fs\n", time);