use of "&" operator in conditional statement in C++ [duplicate] - c++

This question already has answers here:
why does this work? (finding odd number in c++)
(9 answers)
Closed 2 years ago.
int main()
int n=5;
if(n & 1)
cout<<"odd";
else
cout<<"even";
how we are getting even or out using "&" operator
it should have been like this
if(n%2!=0) to check the even or odd.
can anyone explain what is that code doing.

What "n & 1" does here is that it returns the bitwise AND between n and 1. In other words, this is checking whether the last bit of n is equal to 1.
If it is, then n is odd, because the least significant bit of all binary representations of odd numbers is 1. If it's not, then n is even, because the least significant bit of all binary representations of even numbers is 0.

Related

C++ is saying that -1 < 13 (in programming) is false [duplicate]

This question already has answers here:
Why does this if conditional with string.length() evaluate inconsistently?
(2 answers)
Signed/unsigned comparisons
(6 answers)
Weird std::string::size() in a for loop
(2 answers)
Closed 5 months ago.
I have a string called in, a string that has the value of Hello, world!. I also have a integer called i that has the value -1. When I ask C++ to print out if i is less than the length of in (in.length()), it says false but when I try -1 < 15, it says true. Why does it say false? I feel like this is extremely basic math?
string::length() returns an unsigned integer. You can't compare that to a negative signed value, so the -1 gets converted to an unsigned value, which wraps it to a very large number, which is not less than the string's length, hence the result is false.
-1 < 15, on the other hand, is comparing two signed integers, so no conversion is needed, and the result is true, as expected.

why (-1) % vector::size() always returns 0 [duplicate]

This question already has answers here:
Modular operation (%) provides false output
(3 answers)
Closed 2 years ago.
I wrote this code in C++.
vector<int> array = {1,2,3,4};
int i = (-1) % array.size();
Value i always has 0, but I want to get -1.
When I change the code into this with cast.
vector<int> array = {1,2,3,4};
int i = (-1) % (int)array.size();
Then i has -1.
I searched some attribute of vector::size() function in the internet.
However, I didn't understand.
Can anyone answer why this happens.
Thanks a lot.
Thanks for comment lgor.
This is surely because (-1) % array.size() converts int -1 to size_t. Thus becoming 0xFFFF... depending on the exact type of size_t. Taking it modulo 4 results in 3.
Not sure why you got 0. Probably in your code size of the array was 3 despite what you wrote - in which case result would be 0.
Edit: see the arithmetic conversion rules as to why the computation is done in size_t and not another type: https://en.cppreference.com/w/cpp/language/operator_arithmetic

Improve readability of very large constants in C++ [duplicate]

This question already has answers here:
Representing big numbers in source code for readability?
(5 answers)
Closed 7 years ago.
In C++, sometimes you want to declare large numbers. Sometimes it's hard to see if you have the right number of zeroes.
const long long VERY_LARGE_NUMBER = 300000000000;
In a language like OCaml, you can separate numbers with underscores to improve readability.
let x = 300_000_000_000;;
Is there a similar mechanism in C++? I have seen things like = 1 << 31 for powers of 2, but what about for very large powers of 10? Sometimes you're declaring very large numbers (e.g. array bounds in competition programming) and you want to be confident that your declared array size is correct.
I can think of something like:
const long long VERY_LARGE_NUMBER = 3 * (1 << (11 * 10 / 3));
...which abuses 1<<10 ~= 1000 get close to 3 with 11 zeroes, but it's verbose and not exact.
how about
const long long VERY_LARGE_NUMBER = (long long) 300 * 1000 * 1000 * 1000;
Since C++14, integer literal supports the use of ' as a delimiter. For example, unsigned long long l2 = 18'446'744'073'709'550'592llu;. See this cppreference page for the details. Also, you may consider using scientific notation, like 123e4. Such literals are floating point literals. But you can convert them to integer types.

Difference between (n&1) and n&1 [duplicate]

This question already has answers here:
Operator precedence (bitwise '&' lower than '==')
(3 answers)
Closed 8 years ago.
I was trying to solve a Counter Game problem:
"Louise and Richard play a game. They have a counter set to N. Louise gets the first turn and the turns alternate thereafter. In the game, they perform the following operations.
If N is not a power of 2, they reduce the counter by the largest power of 2 less than N.
If N is a power of 2, they reduce the counter by half of N.
The resultant value is the new N which is again used for subsequent operations.
The game ends when the counter reduces to 1, i.e., N == 1, and the last person to make a valid move wins.
Given N, your task is to find the winner of the game."
To solve the question, I implemented bit manipulation, and got accepted:
#include <iostream>
#include <cstdio>
int main() {
long long unsigned int n, tmp;
int cnt, t;
scanf("%d", &t);
while(t--) {
scanf("%llu", &n), tmp=n;
cnt=0;
while(tmp) tmp&=tmp-1, cnt++;
cnt--;
while((n&1)==0) n>>=1, cnt++;
if(cnt%2==0) printf("Richard\n");
else printf("Louise\n");
}
return 0;
}
However, during the coding i coded while(n&1==false) instead of while((n&1)==false), thus could not get desired result. Coding while(!(n&1)) gave expected result, but that(!a instead of a==false) was bad practice due to some sources(I forgot them) I have read online. And I know the difference between while(!n&1) and while(!(n&1)), but I did not know while(n&1==false) and while((n&1)==false). Learnt the latter was and is dissimilar, and may I ask the distinction, please?
This is considered by many a design mistake of C.
While it's natural that a logical-and operation should have lower precedence than equality comparison the same is much more questionable for bitwise-and because bitwise operations are naturally closer to math operations.
The same design error has been inherited by C++ for backward compatibility.
A good rule is always parenthesize bitwise operations to avoid surprises.
As you can see here, the precedence of == is above the precedence of &.
Therefore n&1==false is interpreted as n&(1==false) not (n&1)==false, so you need the parentheses.
== has higher priority in C++ than & (source).
Thus while(n&1==false) is treated as while (n & (1 == false)) which actually is while (n & 0).

Adding long numbers gives me minus result? [duplicate]

This question already has answers here:
How disastrous is integer overflow in C++?
(3 answers)
Closed 8 years ago.
when i try to add two long numbers it gives me minus result :
#include<iostream>
using namespace std;
int main ()
{
int a=1825228665;
int b=1452556585;
cout<<a+b;
return 0;
}
This gives me:
-1017182046
It's overflowing of the type. When you add two big number that the result can't be stored in chosen type it get overfloved. In most cases it will wraped the number, but it's not defined in the standard. So in some compilers the result is undefined.
For int and other numeric types when program can't store this big number in it we can see a overflow of it.
Lets say that int can store number from -10 to 10, when you do this:
int a = 10;
int b = a+1;
You will get -10 in b or some random value (it can be anything because the result is undefined)
That's because the results overflows. Since the first bit in numeric signed data types is used for the sign representation. The specific representation is called Two's complement (Wikipedia article here). Practically a 1 in this bit maps to a - while a 0 to +. The solution to this problem is using a larger data type like long. Larger it means that the memory used to store it is bigger so the range of values increases.