The following function is claimed to evaluate whether a number is integer power of 4. I do not quite understand how it works?
bool fn(unsigned int x)
{
if ( x == 0 ) return false;
if ( x & (x - 1) ) return false;
return x & 0x55555555;
}
The first condition rules out 0, which is obviously not a power of 4 but would incorrectly pass the following two tests. (EDIT: No, it wouldn't, as pointed out. The first test is redundant.)
The next one is a nice trick: It returns true if and only if the number is a power of 2. A power of two is characterized by having only one bit set. A number with one bit set minus one results in a number with all bits previous to that bit being set (i.e. 0x1000 minus one is 0x0111). AND those two numbers, and you get 0. In any other case (i.e. not power of 2), there will be at least one bit that overlaps.
So at this point, we know it's a power of 2.
x & 0x55555555 returns non-zero (=true) if any even bit it set (bit 0, bit 2, bit 4, bit 6, etc). That means it's power of 4. (i.e. 2 doesn't pass, but 4 passes, 8 doesn't pass, 16 passes, etc).
Every power of 4 must be in the form of 1 followed by an even number of zeros (binary representation): 100...00:
100 = 4
10000 = 16
1000000 = 64
The 1st test ("if") is obvious.
When subtracting 1 from a number of the form XY100...00 you get XY011...11. So, the 2nd test checks whether there is more than one "1" bit in the number (XY in this example).
The last test checks whether this single "1" is in the correct position, i.e, bit #2,4,6 etc. If it is not, the masking (&) will return a nonzero result.
Below solution works for 2,4,16 power of checking.
public static boolean isPowerOf(int a, int b)
{
while(b!=0 && (a^b)!=0)
{
b = b << 1;
}
return (b!=0)?true:false;
}
isPowerOf(4,2) > true
isPowerOf(8,2) > true
isPowerOf(8,3) > false
isPowerOf(16,4) > true
var isPowerOfFour = function (n) {
let x = Math.log(n) / Math.log(4)
if (Number.isInteger(x)) {
return true;
}
else {
return false
}
};
isPowerOfFour(4) ->true
isPowerOfFour(1) ->true
isPowerOfFour(5) ->false
Related
I am currently trying to solve a problem set on codeforce where I need to check if an positive integer number has unique digits. My solutions includes a while loop and two for loops, which is quite a lot of for such an easy task.
I found a more elegant solution but I don't fully understand how the code works. I have commented it with my remarks. Could someone explain to me the second 2) and fifth 5) part?
int unique(long long int number){
/* 1) create array/list with 10 elements, the first element seen[0]
* is equal to zero */
char seen[10] = {0};
/* 2) what is the meaning of while(some random integer number)? I thought
* that the argument must be a statement that is either true or false. */
while (number) {
int digit = number % 10; // 3) get the last digit of the number
number /= 10; // 4) removes last digit of the number
/* 5) Could someone explain to me what seen[digit]++ does. And when its
* true or false? */
if (seen[digit]++)
return 0; /* not unique */
}
return 1; /* unique */
}
Of course I tried to figure out the fifth part on my own but
#include <iostream>
using namespace std;
int main(){
char seen[10] = {0};
cout << seen[7]++ << endl;
}
print outs nothing.
I'll go by parts:
2 ) The implicit conversion between a numeric type and bool returns false if the number is zero and true otherwise. You could read while(number) like while(number != 0)
5 ) This works the same way: seen[digit]++ is an expression with the same value as seen[digit] but that then increments its value (check how post-increment works). Therefore, the first time that digit is seen, seen[digit]++ has the value 0 (so the first time the condition is not met) and increments its value to 1 (so the second time the condition will be met, making the function return).
while(number) means the cycle will repeat until number is not zero. Non-zero number is equal to true
seen[digit]++ does following:
it return current value of seen[digit]. For the first time it will be zero - as no number met.
after returning current value - it increase value by one. So for the first call it will return 0 and the seen[digit] will become 1.
So for the second call it will return 1 - that mean this number already met, so it is not unique.
Q.1 what is the meaning of while(some random integer number)? I thought that the argument must be a statement that is either true or false.
=> Yes you are right while condition checks for true and false. In case of integer, 0 is treated as false and rest of the integers as true. So, whenever number become 0, while loop will break.
Q.2 Could someone explain to me what seen[digit]++ does. And when its true or false?
=> seen is declared as an array of size 10 and initialized all entries as 0. So initially every entry of array seen is zero i.e. seen[0] = 0, seen[1] = 0, seen[2] = 1... seen[9] = 0. Now when we find digit and perform seen[digit]++ it will increase value by 1 every time.
Ok so:
Every number not equal to 0 is true and equal to 0 is false. For example 1 2 and 3 are true, but 0 is false. So while (number) will iterate as long as number != 0
seen[digit]++ first returns the value, then increments itself by one after returning the value.
The condition if(number) is same as if(number != 0).
Point 2: After we have processed the last digit in the number, the value of number/10 will be 0 (as the last digit belongs to 0-9) and there we end our loop.
Point 5: The increment number will increment the value in the array and return the old value. If the value is incremented to 2, then it means that the digit is not unique and increment operation returns us 1 and the if condition is satisfied.
In C++ 0 evaluates to false and any other number evaluates to true. That "random number" is actually modified inside the loop with number /= 10. Division of integer numbers in C++ is special in the sense that it does not yield fractions so 51/10 = 5 and 5/10 = 0. At some point number equals 0 and the loop ends.
seen[digit]++ is a commonly used trick. You lookup the table seen at position digit return the current value and increment the value by 1. So if you would modify your example code like this:
#include <iostream>
using namespace std;
int main(){
int seen[10] = {0};
cout << seen[7]++ << endl;
cout << seen[7] << endl;
}
Your console output should be:
0
1
There is also ++seen[digit] which would first increment and then return the value so you would get:
1
1
I am just starting out programming and reading thru C++ Programming Principles and Practice. I am currently doing the Chapter 3 exercises and do not understand why this code I wrote works. Please help explain.
#include "std_lib_facilities.h"
int main() {
cout<<"Hello, User\n""Please enter a number (Followed by the 'Enter' key):";
int number=0;
cin>> number;
if (number%2) {
cout<<"Your number is an odd number!";
} else {
cout<<"Your number is an even number\n";
}
return 0;
}
When number is odd, number%2 is 1.
if (number%2) {
is equivalent to
if (1) {
Hence, you get the output from the line
cout<<"Your number is an odd number!";
When number is even, number%2 is 0.
if (number%2) {
is equivalent to
if (0) {
Hence, you get the output from the line
cout<<"Your number is an even number\n";
The modulus operator simply determines the remainder of the corresponding division problem. For instance, 2 % 2 returns 0 as 2 / 2 is 1 with a remainder of 0.
In your code, any even number entered will return a 0 as all even numbers are, by definition, divisible by 2 (meaning <any even number> % 2 == 0)
Likewise, any odd number entered will return 1 (for instance, 7 % 2 == 1 as 7 / 2 has a remainder of 1).
In c++, like in many programming languages, numeral values can be treated as booleans such that 0 relates to false while other numbers (depending on the language) relate to true (1 is, as far as I know, universally true no matter the programming language).
In other words, an odd number input would evaluate number % 2 to 1, meaning true. So if (number % 2), we know that the input number is odd. Otherwise, number % 2 must be false, meaning 0, which means that the input number is even.
"if" statements works on boolean values. Let's remember that boolean values are represented by "false" and "true", but in reality, it's all about the binary set of Z2 containing {0, 1}. "false" represents "0" and "true" represents "1" (or some people in electronics interpret them as "off/on")
So, yeah, behind the curtains, "if" statements are looking for 0 or 1. The modulus operator returns the rest of a / b. When you input any number and divide it by 2, you are gonna get a rest of 0 or 1 being it pair or an odd number.
So that's why it works, you will always get a result of 0 or 1 which are false and true by doing that operation that way.
think of modulus in terms of this:
while (integer A is bigger than integer B,)
A = A - B;
return A
for example, 9%2 -> 9-2=7-2=5-2=3-2=1
9%2=1;
the statement if (number%2) is what is called a boolean comparison (true false). Another way to write this statement identically is if(number%2 != 0) or if(number%2 != false) since false and zero are equivocal. You're taking the return value of the modulus operator function (a template object we will assume is an integer) and inserting it into an if statement that executes if the input does not equal zero. If statements execute if the input is -5,9999999,1-- anything but zero. So, if (2) would be true. if(-5) would also be true. if(0) would be false. if(5%2) would be 1 = true. if(4%2) would be if(0) = false. If it is true, the code in the body of the if statement is executed.
I can't understand how to count number of 1's in binary representation.
I have my code, and I hope someone can explain it for me.
Code:
int count (int x)
{
int nr=0;
while(x != 0)
{
nr+=x%2;
x/=2;
}
return nr;
}
Why while ? For example if i have 1011, it wouldn't stop at 0?
Why nr += x%2 ?
Why x/=2 ?!
First:
nr += x % 2;
Imagine x in binary:
...1001101
The Modulo operator returns the remainder from a / b.
Now the last bit of x is either a 0, in which case 2 will always go into x with 0 remainder, or a 1, in which case it returns a 1.
As you can see x % 2 will return (if the last bit is a one) a one, thus incrementing nr by one, or not, in which case nr is unchanged.
x /= 2;
This divides x by two, and because it is a integer, drops the remainder. What this means is is the binary was
....10
It will find out how many times 2 would go into it, in this case 1. It effectively drops the last digit of the binary number because in base 2 (binary) the number of times 2 goes into a number is just the same as 'shifting' everything down a space (This is a poor explanation, please ask if you need elaboration). This effectively 'iterates' through the binary number, allowing the line about to check the next bit.
This will iterate until the binary is just 1 and then half that, drop the remainder and x will equal 0,
while (x != 0)
in which case exit the loop, you have checked every bit.
Also:
'count`is possibly not the most descriptive name for a function, consider naming it something more descriptive of its purpose.
nr will always be a integer greater or equal to zero, so you should probably have the return type unsigned int
int count (int x)
{
int nr=0;
while(x != 0)
{
nr+=x%2;
x/=2;
}
return nr;
}
This program basically gives the numbers of set bits in a given integer.
For instance, lets start with the example integer 11 ( binary representation - 1011).
First flow will enter the while loop and check for the number, if it is equal to zero.
while(11 != 0)
Since 11 is not equal to zero it enter the while loop and nr is assigned the value 1 (11%2 = 1).nr += 11%2;
Then it executes the second line inside the loop (x = x/2). This line of code assigns the value 5 (11/2 = 5 ) to x.
Once done with the body of the while loop, it then again checks if x ie 5 is equal to zero.
while( 5 != 0).
Since it is not the case,the flow goes inside the while loop for the second time and nr is assigned the value 2 ( 1+ 5%2).
After that the value of x is divided by 2 (x/2, 5/2 = 2 )and it assigns 2 to x.
Similarly in the next loop, while (2 != 0 ), nr adds (2 + 2%2), since 2%2 is 0, value of nr remains 2 and value of x is decreased to 1 (2/2) in the next line.
1 is not eqaul to 0 so it enters the while loop for the third time.
In the third execution of the while loop nr value is increased to 3 (2 + 1%2).
After that value of x is reduced to 0 ( x = 1/2 which is 0).
Since it fails the check (while x != 0), the flow comes out of the loop.
At the end the value of nr (Which is the number of bits set in a given integer) is returned to the calling function.
Best way to understand the flow of a program is executing the program through a debugger. I strongly suggest you to execute the program once through a debugger.It will help you to understand the flow completely.
Consider two vectors, A and B, of size n, 7 <= n <= 23. Both A and B consists of -1s, 0s and 1s only.
I need a fast algorithm which computes the inner product of A and B.
So far I've thought of storing the signs and values in separate uint32_ts using the following encoding:
sign 0, value 0 → 0
sign 0, value 1 → 1
sign 1, value 1 → -1.
The C++ implementation I've thought of looks like the following:
struct ternary_vector {
uint32_t sign, value;
};
int inner_product(const ternary_vector & a, const ternary_vector & b) {
uint32_t psign = a.sign ^ b.sign;
uint32_t pvalue = a.value & b.value;
psign &= pvalue;
pvalue ^= psign;
return __builtin_popcount(pvalue) - __builtin_popcount(psign);
}
This works reasonably well, but I'm not sure whether it is possible to do it better. Any comment on the matter is highly appreciated.
I like having the 2 uint32_t, but I think your actual calculation is a bit wasteful
Just a few minor points:
I'm not sure about the reference (getting a and b by const &) - this adds a level of indirection compared to putting them on the stack. When the code is this small (a couple of clocks maybe) this is significant. Try passing by value and see what you get
__builtin_popcount can be, unfortunately, very inefficient. I've used it myself, but found that even a very basic implementation I wrote was far faster than this. However - this is dependent on the platform.
Basically, if the platform has a hardware popcount implementation, __builtin_popcount uses it. If not - it uses a very inefficient replacement.
The one serious problem here is the reuse of the psign and pvalue variables for the positive and negative vectors. You are doing neither your compiler nor yourself any favors by obfuscating your code in this way.
Would it be possible for you to encode your ternary state in a std::bitset<2> and define the product in terms of and? For example, if your ternary types are:
1 = P = (1, 1)
0 = Z = (0, 0)
-1 = M = (1, 0) or (0, 1)
I believe you could define their product as:
1 * 1 = 1 => P * P = P => (1, 1) & (1, 1) = (1, 1) = P
1 * 0 = 0 => P * Z = Z => (1, 1) & (0, 0) = (0, 0) = Z
1 * -1 = -1 => P * M = M => (1, 1) & (1, 0) = (1, 0) = M
Then the inner product could start by taking the and of the bits of the elements and... I am working on how to add them together.
Edit:
My foolish suggestion did not consider that (-1)(-1) = 1, which cannot be handled by the representation I proposed. Thanks to #user92382 for bringing this up.
Depending on your architecture, you may want to optimize away the temporary bit vectors -- e.g. if your code is going to be compiled to FPGA, or laid out to an ASIC, then a sequence of logical operations will be better in terms of speed/energy/area than storing and reading/writing to two big buffers.
In this case, you can do:
int inner_product(const ternary_vector & a, const ternary_vector & b) {
return __builtin_popcount( a.value & b.value & ~(a.sign ^ b.sign))
- __builtin_popcount( a.value & b.value & (a.sign ^ b.sign));
}
This will lay out very well -- the (a.value & b.value & ... ) can enable/disable an XOR gate, whose output splits into two signed accumulators, with the first pathway NOTed before accumulation.
Sorry for this newbie question, but I can't find on google what I need to know.
I understand return, but don't understand this... What does it mean this?
return (tail+1)%N == head%N;
Thanks a lot for patience.
It returns true or false, depending on whether the expression is true or not.
It's the same as:
if ( (tail+1)%N == head%N )
return true;
else
return false;
this
(tail+1)%N == head%N
returns a boolean value, either true or false. This statement means that after adding 1 to trail (trail + 1) and the remainder obtained after division with N is equal to remainder of head divided with N. % is used for division with remainder
(%). Modulo is the operation that gives the remainder of a division of two values.
Check this link for c++ operators : http://www.cplusplus.com/doc/tutorial/operators/
you're returning a boolean value. The value represents whether or not the remainder of (tail+1) divided by N is the same as that of head.
It evaluates the expression, and return the result. In this case it's two modulo operations that are compared, and the result is either true or false which will be returned.
Short Answer:
Because of the == operator your function will return a bool, meaning it can only be trueor false. An equivalent would be something like:
return 5 == 4;
which would return false since 5 is not equal to 4.
Long Answer:
Instead of writing this in a single line you could split it up into more lines of code. Let's just assume that tail, head and N are integer values, then you could write it like this:
int x, y;
x = (tail+1)%N;
y = head%N;
if ( x == y )
{
return true;
}
else
{
return false;
}
Now in this code there may be also that %confuses you a bit. The %is called the Modulus Operator and can give you the remainder of arithmetic operations. In a simple example this would mean:
10 % 3 = 1 because 10/3 is 3 with a remainder of 1. So to make it more clear let's just make another example with your specific problem:
Lets just assume that tail=10,head=6 and N=2. Then you would get something like this:
x = (10+1)%2
x = 11 % 2
x = 1
y = 6 % 2
y = 0
y != x
This would return false cause x and y are not equal. ( If you would run your code with the given example values )
To learn more about Modulus you can look here, or just on any other basic C++ Tutorial.
it returns true if remainder of the division for tail + 1 and head is the same
for example if tail is 2, head is 1 and N is 2
(tail + 1) % N is 1
head % N is 1 too
so whole expression returns true