Power of 2 formula help - java

I understand that (2 * i == (i ^( i - 1) + 1) in Java will let me find if a number is a power of two. But can someone explain why this works?

2*i == (i ^ (i-1)) + 1
Basically, if i was a a power of 2, it would have a single 1 in its bit pattern. If you subtract 1 from that, all the lower bits of that 1 bit become 1, and that power-of-two bit will become 0. Then you do an XOR on the bits, which produces an all 1 bit pattern. You add 1 to that, and you get the next power of 2.
Remember XOR truth table:
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
Example:
Let's say i is 256, which is this bit pattern.
100000000 = 2^8 = 256
100000000 - 1 = 011111111 = 2^7 + 2^6 + ... + 2^0 = 255
100000000 ^ 011111111 = 111111111 = = 2^8 + 2^7 + ... + 2^0 = 511
111111111 + 1 = 1000000000 = 2^9 = 512 = 2*i
Here's an example when you are not presented with a power of 2
i = 100 = 2^6 + 2^5 + 2^2
0110 0100
0110 0100 - 1 = 99 = 2^6 + 2^5 + 2^1 + 2^0 = 0110 0011
0110 0100 ^ 0110 0011 = 0000 0111 = 2^2 + 2^1 + 2^0 = 7
0000 0111 + 1 = 000 1000 = 2^3 = 8 != (2*i)
Simplified Version
Also, there's a modified version of this check to determine if some positive, unsigned integer is a power of 2.
(i & (i-1)) == 0
Basically, same rationale
If i is a power of 2, it has a single 1 bit in its bit representation. If you subtract 1 from it, the 1 bit becomes 0, and all the lower bits become 1. Then AND will produce an all 0 bit-pattern.

The important bit is the i^(i-1) (I'm assuming this is a small typo in the question). Suppose i is a power of 2. Then its binary expansion is a 1 followed by many zeroes. i-1 is a number where that leading 1 is replaced by a zero and all the zeroes are replaced by ones. So the result of the XOR is a string of 1's that's the same number of bits as i.
On the other hand, if i isn't a power of 2, subtracting 1 from it won't flip all of those bits - the xor then identifies which bits didn't carry from one place to the next when you subtracted 1. There'll be a zero in the result of the xor, so when you add the 1, it won't carry into the next bit position.

Related

How to reverse this equation?

The following line of code is inside a for loop where j is incremented and ansString is a string of ASCII characters, like 000\Qg$M!*P000\gQYA+ h000\M|$skd 000\Qo}plsd000\.
ansString[j] = ((char)(paramString[j] >> j % 8 ^ paramString[j]));
I am having trouble with figuring out how to have XOR and all the other operators reversed to find paramString. Appreciate any help.
The right bitshift (>>) and modulo (%) are irreversible operations:
In the case of the right bitshift, underflowed bits are lost, so reversing a >> b would leave you with 2^b different possible results.
For the modulo operator, in x % 8 = y there are 32 possible values for x asuming it has a maximum length of 8 bits. (That would be every x * 8 + y that fit in 8 bits)
The xor operation is the only one reversible. If you have
a ^ b = c
then
c ^ b = a
So for more than one input you would have the same output. For example, lets take the case where j = 0
j % 8 = 0 % 8 = 0
paramString[j] >> (j % 8) = paramString[0] >> 0 = paramString[0]
paramString[0] ^ paramString[j] = paramString[0] ^ paramString[0] = 0
This means that for your first character and every 8th subsequent character (this is every character where its index j is a multiple of 8, so j % 8 = 0) the result will be 0, whichever the original character was (as you can see in your example output string).
This is why, even if you brute-force every possible input (a total of 256 * n possible input strings, being n the string length), you can never be sure of what was the original input, as many inputs yield the same output.
If j is a running index, you will know the shift amount in each iteration. With that, you can find a prefix and decrypt the string.
e.g. for j = 2 (0..7 are bit positions, double digits are XORed bits, x is 0):
Original: 0 1 2 3 4 5 6 7
Shifted: x x 0 1 2 3 4 5
Encrypted: 0 1 02 13 24 35 46 57
As you can see, the first 2 digits remain untouched. And those 2 digits are used to encrypt the next two, and so forth.
So to decrypt with j = 2, you find a 2 digit prefix unencrypted. This can be used to decrypt the next 2 bits (02 and 13):
Encrypted: 0 1 02 13 24 35 46 57
Shift-Mask: x x 0 1 x x x x
Temp1: 0 1 2 3 24 35 46 57
Now we know the first 4 digits, and also the decryption bits for the next 2:
Temp1: 0 1 2 3 24 35 46 57
Shift-Mask: x x x x 2 3 x x
Temp2: 0 1 2 3 4 5 46 57
And again:
Temp2: 0 1 2 3 4 5 46 57
Shift-Mask3: x x x x x x 4 5
Decrypted3: 0 1 2 3 4 5 6 7 <- Original string
Based on this idea, you can build the decryption algorithm

How to negate base -2 numbers?

I was given a Codility test lately and I was wondering how can I negate -2 base numbers?
For example the array [1,0,0,1,1] represents 9 in base -2:
-2 bases:
1,-2,4,-8,16
1 + (-8) + 16 = 9
[1,0,0,1,1]
Negative 9 in base -2 is:
-2 bases:
1,-2,4,-8
1 + (-2) + -8 = -9
[1,1,0,1]
I'm in the dark regarding the question. There must be some intuitive solution for this. Do you have any hints?
In base −2, a 1 at position i means (−2)i.
So, a [1,1] in positions [i,i+1] means (−2)i + (−2)i+1 = (−2)i + (−2)(−2)i = (1 + −2)(−2)i = −(−2)i.
So you can negate any occurrence of a [1,0] by changing it to a [1,1], and vice versa.
Any other occurrences of 0, of course, can be left intact: −0 = 0.
So in your example, we split [1,0,0,1,1] into [{1,0}, {0}, {1,1}], negate each part to get [{1,1}, {0}, {1,0}], i.e., [1,1,0,1,0], and remove the unnecessary high 0, producing [1,1,0,1].
Let's try a few examples:
(16 -8 4 -2 1)
1 = 0 0 0 0 1
-1 = 0 0 0 1 1
2 = 0 0 1 1 0
-2 = 0 0 0 1 0
3 = 0 0 1 1 1
-3 = 0 1 1 0 1
4 = 0 0 1 0 0
-4 = 0 1 1 0 0
5 = 0 0 1 0 1
-5 = 0 1 1 1 1
We can try to define this mathematically:
Given input I(b) (where B is the bit number),
I = ∑(-2)bI(b) -- definition of base -2)
O = -I -- what we're trying to solve for
O = -∑(-2)bI(b) -- substitution
O = ∑-(-2)bI(b) -- distribution
-(-2)b = (-2)b + (-2)b+1
O = ∑((-2)b + (-2)b+1)I(b) -- substitution
O = ∑((-2)bI(b) + (-2)b+1I(b)) -- substitution
O = ∑(-2)bI(b) + ∑(-2)b+1I(b)
O(b) = I(b) + I(b-1)
Now, this leaves the possibility that O(b) is 0, 1, or 2, since I(b) is always 0 or 1.
If O(b) is a 2, that is a "carry", Let's look at a few examples of carries:
(16 -8 4 -2 1) (16 -8 4 -2 1)
1+1 = 0 0 0 0 2 = 0 0 1 1 0
-2-2 = 0 0 0 2 0 = 0 1 1 0 0
4+4 = 0 0 2 0 0 = 1 1 0 0 0
for each b, starting at 0, if O(b) >= 2, subtract 2 from O(b) and increment O(b+1) and O(b+2). Do this until you reach your maximum B.
Hopefully this explains it in enough detail.
Imagine you have a number A. Then -A = A - 2*A
Or -A = A + (-2)*A. Luckily you have base -2. And (-2)*A is equivalent to left shift by one digit. All you need now is just to implement A << 1 + A. Array shifting is easy. And then you need to implement binary addition with one small difference: each time you carry over a bit you need to multiply it by -1.
public int[] solution(int[] input)
{
var A = new int[input.Length + 1];
var B = new int[input.Length + 1];
input.CopyTo(B, 1);
input.CopyTo(A, 0);
return GetResult(A, B).ToArray();
}
public IEnumerable<int> GetResult(int[] A, int[] B)
{
var r = 0;
for (int i = 0; i < A.Length; i++)
{
var currentSum = A[i] + B[i] + r;
r = -currentSum / 2;
yield return currentSum % 2;
}
}
Sorry, but the example is in C#

How to (cheaply) calculate all possible length-r combinations of n possible elements

What is the fastest way to calculate all possible length-r combinations of n possible elements without resorting to brute force techniques or anything that requires STL?
While working on an Apriori algorithm for my final project in my data structures class, I developed an interesting solution that uses bit-shifting and recursion, which i will share in an answer below for anyone who is interested. However, is this the fastest way of achieving this (without using any common libraries)?
I ask more out of curiosity than anything else, as the algorithm i currently have works just fine for my purposes.
Here is the algorithm that i developed to solve this problem. It currently just outputs each combination as a series of ones and zeros, but can be easily adapted to create data sets based on an array of possible elements.
void r_nCr(const unsigned int &startNum, const unsigned int &bitVal, const unsigned int &testNum) // Should be called with arguments (2^r)-1, 2^(r-1), 2^(n-1)
{
unsigned int n = (startNum - bitVal) << 1;
n += bitVal ? 1 : 0;
for (unsigned int i = log2(testNum) + 1; i > 0; i--) // Prints combination as a series of 1s and 0s
cout << (n >> (i - 1) & 1);
cout << endl;
if (!(n & testNum) && n != startNum)
r_nCr(n, bitVal, testNum);
if (bitVal && bitVal < testNum)
r_nCr(startNum, bitVal >> 1, testNum);
}
How it works:
This function treats each combination of elements as a sequence of ones and zeros, which can then be expressed with respect to a set of possible elements (but is not in this particular example).
For example, the results of 3C2 (all combinations of length-2 from a set of 3 possible elements) can be expressed as 011, 110, and 101. If the set of all possible elements is {A, B, C}, then the results can be expressed with respect to this set as {B, C}, {A, B}, and {A, C}.
For this explanation, i will be calculating 5C3 (all length-3 combinations composed of 5 possible elements).
This function accepts 3 arguments, all of which are unsigned integers:
The first parameter is the smallest possible integer whose binary representation has a number of 1s equal to the length of the combinations we're creating. This is out starting value for generating combinations. For 5C3, this would be 00111b, or 7 in decimal.
The second parameter is the value of highest bit that is set to 1 in the starting number. This is the first bit that will be subtracted when creating the combinations. For 5C3, this is the third bit from the right, which has a value of 4.
The third parameter is the value of the nth bit from the right, where n is the number of possible elements that we are combining. This number will be bitwise-anded with the combinations we create to check whether the left-most bit of the combination is a 1 or a 0. For 5C3, we will use the 5th bit from the right, which is 10000b, or 16 in decimal.
Here are the actual steps that the function performs:
Calculate startNum - bitVal, bit-shift one space to the left, and add 1 if bitVal is not 0.
For the first iteration, the result should be the same as startNum. This is so that we can print out the first combination (which is equal to startNum) within the function so we don't have to do it manually ahead of time. The math for this operation occurs as follows:
00111 - 00100 = 00011
00011 << 1 = 00110
00110 + 1 = 00111
The result of the previous calculation is a new combination. Do something with this data.
We are going to be printing the result to the console. This is done using a for-loop whose variable starts out equal to the number of bits we are working with (calculated by taking log2 of the testNum and adding 1; log2(16) + 1 = 4 + 1 = 5) and ends at 0. Each iteration, we bit-shift right by i-1 and print the right-most bit by and-ing the result with 1. Here is the math:
i=5:
00111 >> 4 = 00000
00000 & 00001 = 0
i=4:
00111 >> 3 = 00000
00000 & 00001 = 0
i=3:
00111 >> 2 = 00001
00001 & 00001 = 1
i=2:
00111 >> 1 = 00011
00011 & 00001 = 1
i=1:
00111 >> 0 = 00111
00111 & 00001 = 1
output: 00111
If the left-most bit of n (the result of the calculation in step 1) is 0 and n is not equal to startNum, we recurse with n as the new startNum.
Obviously this will be skipped on the first iteration, as we have already shown that n is equal to startNum. This becomes important in subsequent iterations, which we will see later.
If bitVal is greater than 0 and less than testNum, recurse with the current iteration's original startNum as the first argument. Second argument is bitVal shifted right by 1 (same thing as integer division by 2).
We now recurse with the new bitVal set to the value of the next bit to the right of the current bitVal. This next bit is what will be subtracted in the next iteration.
Continue to recurse until bitVal becomes equal to zero.
Because bitVal is bit-shifted right by one in the second recursive call, we will eventually reach a point when bitVal equals 0. This algorithm expands as a tree, and when bitVal equals zero and the left-most bit is 1, we return to one layer up from our current position. Eventually, this cascades all the way back the the root.
In this example, the tree has 3 subtrees and 6 leaf nodes. I will now step through the first subtree, which consists of 1 root node and 3 leaf nodes.
We will start at the last line of the first iteration, which is
if (bitVal)
r_nCr(startNum, bitVal >> 1, testNum);
So we now enter the second iteration with startNum=00111(7), bitVal = 00010(2), and testNum = 10000(16) (this number never changes).
Second Iteration
Step 1:
n = 00111 - 00010 = 00101 // Subtract bitVal
n = 00101 << 1 = 01010 // Shift left
n = 01010 + 1 = 01011 // bitVal is not 0, so add 1
Step 2: Print result.
Step 3: The left-most bit is 0 and n is not equal to startNum, so we recurse with n as the new startNum. We now enter the third iteration with startNum=01011(11), bitVal = 00010(2), and testNum = 10000(16).
Third Iteration
Step 1:
n = 01011 - 00010 = 01001 // Subtract bitVal
n = 01001 << 1 = 10010 // Shift left
n = 10010 + 1 = 10011 // bitVal is not 0, so add 1
Step 2: Print result.
Step 3: The left-most bit is 1, so do not recurse.
Step 4: bitVal is not 0, so recurse with bitVal shifted right by 1. We now enter the fourth iteration with startNum=01011(11), bitVal = 00001(1), and testNum = 10000(16).
Fourth Iteration
Step 1:
n = 01011 - 00001 = 01010 // Subtract bitVal
n = 01010 << 1 = 10100 // Shift left
n = 10100 + 1 = 10101 // bitVal is not 0, so add 1
Step 2: Print result.
Step 3: The left-most bit is 1, so do not recurse.
Step 4: bitVal is not 0, so recurse with bitVal shifted right by 1. We now enter the fifth iteration with startNum=01011(11), bitVal = 00000(0), and testNum = 10000(16).
Fifth Iteration
Step 1:
n = 01011 - 00000 = 01011 // Subtract bitVal
n = 01011 << 1 = 10110 // Shift left
n = 10110 + 0 = 10110 // bitVal is 0, so add 0
// Because bitVal = 0, nothing is subtracted or added; this step becomes just a straight bit-shift left by 1.
Step 2: Print result.
Step 3: The left-most bit is 1, so do not recurse.
Step 4: bitVal is 0, so do not recurse.
Return to Second Iteration
Step 4: bitVal is not 0, so recurse with bitVal shifted right by 1.
This will continue on until bitVal = 0 for the first level of the tree and we return to the first iteration, at which point we will return from the function entirely.
Here is a simple diagram showing the function's tree-like expansion:
And here is a more complicated diagram showing the function's thread of execution:
Here is an alternate version using bitwise-or in place of addition and bitwise-xor in place of subtraction:
void r_nCr(const unsigned int &startNum, const unsigned int &bitVal, const unsigned int &testNum) // Should be called with arguments (2^r)-1, 2^(r-1), 2^(n-1)
{
unsigned int n = (startNum ^ bitVal) << 1;
n |= (bitVal != 0);
for (unsigned int i = log2(testNum) + 1; i > 0; i--) // Prints combination as a series of 1s and 0s
cout << (n >> (i - 1) & 1);
cout << endl;
if (!(n & testNum) && n != startNum)
r_nCr(n, bitVal, testNum);
if (bitVal && bitVal < testNum)
r_nCr(startNum, bitVal >> 1, testNum);
}
What about this?
#include <stdio.h>
#define SETSIZE 3
#define NELEMS 7
#define BYTETOBINARYPATTERN "%d%d%d%d%d%d%d%d"
#define BYTETOBINARY(byte) \
(byte & 0x80 ? 1 : 0), \
(byte & 0x40 ? 1 : 0), \
(byte & 0x20 ? 1 : 0), \
(byte & 0x10 ? 1 : 0), \
(byte & 0x08 ? 1 : 0), \
(byte & 0x04 ? 1 : 0), \
(byte & 0x02 ? 1 : 0), \
(byte & 0x01 ? 1 : 0)
int main()
{
unsigned long long x = (1 << SETSIZE) -1;
unsigned long long N = (1 << NELEMS) -1;
while(x < N)
{
printf ("x: "BYTETOBINARYPATTERN"\n", BYTETOBINARY(x));
unsigned long long a = x & -x;
unsigned long long y = x + a;
x = ((y & -y) / a >> 1) + y - 1;
}
};
It should print 7C3.

Division by subtration - dividing the remainder by subtration?

We can divide a number by subtraction and stop at the remainder as shown here.
But how do we continue to divide the remainder by subtraction ? I looked on google and could not find such answers. They don't go beyond the remainder.
For example, lets say we have
7/3.
7-3 = 4
4-3 = 1
So, we have 2 & (1/3). How do we do the 1/3
division using only subtraction or addition ?
REPEAT -
Please note that I dont want to use multiplication or division operators to do this.
You can get additional "digits", up to any arbitrary precision (in any base you desire, I'll use base 10 for simplicity but if you're trying to implement an algorithm you'll probably choose base 2)
1) Perform division as you've illustrated, giving you a quotient (Q=2), a divisor (D=3), and a remainder (R=1)
2) If R=0, you're done
3) Multiply R by your base (10, R now =10)
4) Perform division by subtraction again to find R/D (10/3 = 3+1/3).
5) Divide the resulting quotient by your base (3/10 = 0.3) and add this to what you got from step 1 (now your result is 2.3)
6) Repeat from step 2, dividing the new remainder (1) by 10 again
While it sounds an awful lot like I just said division quite a few times, we're dividing by your base. I used 10 for simplicity, but you'd really use base 2, so step 3 is really a left shift (by 1 bit every time) and step 5 is really a right shift (by 1 bit the first time through, 2 bits the second, and so on).
7/3.
7-3 = 4
4-3 = 1
7/3 = 2 R 1
1*10 = 10
10-3 = 7
7-3 = 4
4-3 = 1
10/3 = 3 R 1
7/3 = 2 + 3/10 R 1
7/3 = 2.3 R 1
1*10 = 10
10-3 = 7
7-3 = 4
4-3 = 1
10/3 = 3 R 1
7/3 = 2.3 + 3/100 R 1
7/3 = 2.33 R 1
And so on until you reach any arbitrary precision.
If you want to keep going to get decimal digits, multiply the remainder by a power of 10.
E.g. if you want 2.333, then you can multiply remainder by 1000, and then repeat the algorithm.
It depends on what you are asking.
If you are asking how to get the end fraction and simply it, let's take a different example.
26 / 6.
26 - 6 = 20 count 1
20 - 6 = 14 count 2
14 - 6 = 8 count 3
8 - 6 = 2 count 4
(In code, this would be accomplished with a for loop)
Afterwards, we would have 4 2/6. To simplify, switch the dividend and divisor:
6 / 2.
6 - 2 = 4 count 1
4 - 2 = 2 count 2
2 - 2 = 0 count 3
If this finishes without a remainder, show as 1 over the count.
In pseudo-code:
int a = 26;
int b = 6;
int tempb = 6;
int left = 26;
int count = 0;
int count2 = 0;
left = a - b;
for(count; left > b; count++){
left -= b;
}
if(left > 0){
for(count2; tempb > left; count2++){
tempb -= left;
}
console.log("The answer is " + count + " and 1/" + count2);
I hope this answers your question!
Here is a complete program that uses only + and -, translate to your language of choice:
module Q where
infixl 14 `÷` `×`
a × 0 = 0
a × 1 = a
a × n = a + a×(n-1)
data Fraction = F Int [Int]
a ÷ 0 = error "division by zero"
a ÷ 1 = F a []
0 ÷ n = F 0 []
a ÷ n
| a >= n = case (a-n) ÷ n of
F r xs -> F (r+1) xs
| otherwise = F 0 (decimals a n)
where
decimals a n = case (a × 10) ÷ n of
F d rest = (d:rest)
instance Show Fraction where
show (F n []) = show n
show (F n xs) = show n ++ "." ++ concatMap show (take 10 xs)
main _ = println (100 ÷ 3)
It is easy to extend this in such a way that the periodic part of the fraction is detected, if any. For this, the decimals should be tuples, where not only the fractional digit itself but also the dividend that gave rise to it is kept.
The printing function could then be adjusted to print infinite fractions like 5.1(43), where 43 would be the periodic part.

Need to analyze a set of vectors with 0 and positive integers

I am using Matlab, and I have a 1x200 vector of numbers.
I need to assign a "score" to the set of numbers by following these rules:
If there are 2 or 3 or 4 consecutive positive numbers, then 0.5 points
If there are five or more consecutive positive numbers, then 1.0 points
If there isn't any consecutive positive number, for example: 0 0 0 6 0 0, then 0.0 point. (ignore it, consider that positive number as zero)
If there is only one zero in the middle of a run of positive integers, then ignore that zero (consider it as a positive integer)
If there are two or more consecutive zeroes, that breaks the run of consecutive positive numbers.
Example: 30 43 54 0 0 0 41 54 14 10 1 0 0 0 0 32 41 98 12 0 0 0 (2.0 points total)
At the end, there should be a tally of the points.
Are there any useful functions for this type of problem?
This is based on my understanding of the question, as noted in my question above. I've "unsuppressed" all output, so you can see what's going on.
%Rules:
%1. If there are 2 or 3 or 4 consecutive positive numbers, then 0.5 point
%2. If there are five or more consecutive positive numbers, then 1.0 point
%3. And if there isn't any consecutive positive number, for example:
% 0 0 0 6 0 0, then 0.0 point. (ignore it, consider that positive
% number as zero)
%4. if there is only one zero in the middle of positive integers = ignore
% that zero (consider it as a positive integer)
%5. If there are two or more consecutive 0, THEN no point.
%testData = [0 30 43 54 0 0 0 41 54 14 10 1 0 0 0 0 32 41 98 12 0 0 0 1 2 0 1 2 0 ];
testData = [30 43 54 0 0 0 41 54 14 10 1 0 0 0 0 32 41 98 12 0 0 0 ];
posa = testData>0;
%add 0s at each end so that the diffs at the ends work.
diffa = diff([0 posa 0])
starts = find(diffa ==1)
ends = find(diffa==-1)
% Rule 4 if any end (-1) is immediately followed by a start, that means that there
% is a 0 in the middle of a run. substitute a 1 in the position and recalc.
midZeroLengths = starts(2:end) - ends(1:(end-1));
%pad to account for the fact that we only compared part.
midZeroLengths = [midZeroLengths 0];
if any(midZeroLengths == 1);
testData(ends(midZeroLengths==1)) = 1;
posa = testData>0;
%add 0s at each end so that the diffs at the ends work.
diffa = diff([0 posa 0])
starts = find(diffa ==1)
ends = find(diffa==-1)
end
runs = ends-starts
halfs = (runs > 1) & (runs < 5)
wholes = (runs > 4)
final = sum(halfs)*0.5 + sum(wholes)
How about:
str = repmat('a', 1, numel(testData));
str(testData > 0) = 'b';
m = regexp(str, 'b+(ab+)*', 'match');
n = cellfun(#numel, m);
score = 0.5 * sum(n >= 2 & n <= 4) + 1.0 * sum(n >= 5);
Note that I haven't run this, so there may be errors.

Categories