What is the simplest way to calculate the amount of even numbers in a range of unsigned integers?
An example: if range is [0...4] then the answer is 3 (0,2,4)
I\
Answer is to use binary AND.
so a number is represented in memory in 0 and 1. lets say 4 and 5.
4 = 0000 0100
5 = 0000 0101
and every even number has a zero in the end and every odd number has 1 in the end;
in c '1' means true and '0' means false.
so: lets code;
function isEven(int num){
return ((num & 0x01) == 0) ? 1 : 0;
}
Here 0x01 means 0000 0001. so we are anding 0x01 with the given number.
imagine no is 5
5 |0000 0101
0x01 |0000 0001
---------------
0000 0001
so answer will be '1'.
imagine no is 4
4 |0000 0100
0x01 |0000 0001
---------------
0000 0000
so answer will be '0'.
now,
return ((num & 0x01) == 0) ? 1 : 0;
it is expanded in :
if((num & 0x01) == 0){// means the number is even
return 1;
}else{//means no is odd
return 0;
}
So this is all.
End is binary operatiors are very important in compititive programming world.
happy coding.
first answer here.
EDIT 1:
Total no of evens are
totalEvens = ((end - start) / 2 + ((((end - start) & 0x01 ) == 0) ? 0 : 1 ));
here
(end - start)/2
gives the half of total numbers.
this works if one is even and one is odd.
but,
((((end - start) & 0x01 ) == 0) ? 0 : 1 )
can just replaced by (!isEven(end-start))
So, if the total number is even then dont add 1 else add 1.
this completely works.