Why are such two methods functionally equivalent from a mathematical perspective?

43 Views Asked by At

To program a function that tests whether all elements in an array are greater than 5, the straightforward way will be:

bool test(std::vector<int> arr){
   int number = 0;
   for(auto i:arr){  // Iterate over all elements
       if(i>5){
         number++;
       }
   }
   return arr.size() == number;
}

However, we can also achieve the function in this way:

bool test2(std::vector<int> arr){
   for(auto i:arr){  // Iterate over all elements
      if(i<=5){
        return false;
      }
   }
   return true;
}

Why is test2 functionally equivalent to test? How to interpret them from a mathematical perspective?

test do the things like ∀x ∈ arr, if x > 5, the result is true while test2 do the things like ∃x ∈ arr, if x<=5, the result is false. How do such two propositions mutually exclusive? Or, they are not propositions?

1

There are 1 best solutions below

4
On

This is called De Morgan's Laws. See: https://en.wikipedia.org/wiki/De_Morgan%27s_laws

The intuition behind it is that, if I said every rose is red, that is equivalent to !(there exists at least one rose that isn't red) where ! negates the meaning of the statement or operand. This is because when negating an AND you have to distribute the negation operator which "converts" the AND to an OR and vice versa.

EDIT: Thought it worth adding after OPs comment that the wikipedia page gives this exact formulation: