逻辑与(&&)
在使用&&(逻辑AND)时,我们必须首先将条件变为假的可能性很高,以便如果第一个条件为假,则编译器无需检查第二个条件。
#include
// Function to check whether n is odd
bool isOdd(int n);
// Function to check whether n is prime
bool isPrime(int n);
int main()
{
int cnt = 0, n = 10;
// Implementation 1
for (int i = 2; i <= n; i++) {
if (isOdd(i) && isPrime(i))
cnt++;
}
cnt = 0;
n = 10;
// Implementation 2
for (int i = 2; i <= n; i++) {
if (isPrime(i) && isOdd(i))
cnt++;
}
}
考虑上面的实现:
In implementation 1, we avoid checking even numbers whether they are prime or not as primality test requires more computation than checking a number for even/odd.
Probability of a number getting odd is more than of it being a prime that’s why we first check whether the number is odd before checking it for prime.
On the other hand in implementation 2, we are checking whether the number is prime or not before checking whether it is odd which makes unnecessary computation as all even numbers other than 2 are not prime but the implementation still checks them for prime.
逻辑或(||)
在使用||时(逻辑或),我们必须首先将条件变为真的可能性很高,这样,如果第一个条件为真,则编译器无需检查第二个条件。
#include
// Function to check whether n is odd
bool isEven(int n);
// Function to check whether n is prime
bool isPrime(int n);
int main()
{
int cnt = 0, n = 10;
// Implementation 1
for (int i = 3; i <= n; i++) {
if (isEven(i) || !isPrime(i))
cnt++;
}
}
As described earlier that the probability of a number being even is more than that of it being a non-prime. The current order of execution of the statements doesn’t allow even numbers greater than 2 to be checked whether they are non-prime (as they are all non-primes).
注意:对于较大的输入,语句的执行顺序可能会影响程序的总体执行时间。
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。