Assume a mathematical vector (which is just a 1-D matrix) containing
n numbers in
Z .
For C++ this means that the range of the vector is:
Numbers [0...n) .
The task is to find all possible odd and even
product pairs (all permitations, not combinations).
Or more formally:
ep = | {(i,j) :: 0 <= i < n AND 0 <= j < n AND even(Numbers[ i ] * Numbers[ j ]) |
op = | {(i,j) :: 0 <= i < n AND 0 <= j < n AND odd(Numbers[ i ] * Numbers[ j ]) |
I'll give you the full working code below which does that precisely. However, with the type of mathematical problem as stated above my code is totally unacceptable! This direct method is called:
canonical form.
Your task:
Improve my code so the run-time complexity decreases from a horrible N^2 to N.
Motivation:
Here lies the foundation of classical programming. These kind of problems are for any coder to solve if you take yourself serious.
Code:
#include <iostream>
#include <cstdlib>
void odd_even_pairs(const int* vec, std::size_t size, unsigned& ep, unsigned& op);
void odd_even_pairs_fast(const int* vec, std::size_t size, unsigned& ep, unsigned& op);
bool even(int num);
static const int Numbers[] = {12, 4, 6, 3, 7, 9, 10 , 44, 63, 63, 23, 34, 36,
346, 43, 61, 56, 264, 2463, 25, 2544, 14, 14, 11, 99, 345, -5, -34, -24};
int main()
{
unsigned ep(0), op(0);
std::size_t size(0);
size = sizeof Numbers / sizeof *Numbers;
odd_even_pairs_fast(Numbers, size, ep, op);
std::cout<<"Even pairs: " << ep << std::endl;
std::cout<<"Odd pairs: " << op <<std::endl;
return 0;
}
//------------------------------------
bool even(int num)
{
return ((num % 2) == 0);
}
//-------------------------------------
void odd_even_pairs(const int* vec, std::size_t size, unsigned& ep, unsigned& op)
{
for(std::size_t i = 0; i < size; ++i)
{
for(std::size_t j = 0; j < size; ++j)
{
if( even(vec[i] * vec[j]) )
{
++ep;
}
else
{
++op;
}
}
}
}
//-------------------------------------
void odd_even_pairs_fast(const int* vec, std::size_t size, unsigned& ep, unsigned& op)
{
//TO DO BY STUDENT
}