Beginner explanation to Bitwise operands - java

I am currently taking Intro programming classes. We are learning Java SE (eventually moving up to Java EE). I have a grasp on most things, but I hit a wall with bitwise manipulation and masking. For example:
EDITED HERE:
I want to figure out if a number is divisible by 3 and 5, but not 2. The only requirements is that I can not use % to find the answer, it has to be in a method call, and I have to use masking and bitwise operands.
I already learned how to determine if a number is odd or even with this:
public static boolean isEven(int num) {
return ((num & 1) == 0);
}
I understand what the bitwise operands (&, |, ^, >> , <<) do but can't actually implement them properly. Our book also does not have information on this, it's from our teachers notes.
I'm not asking for just the answer, I need to understand how it actually works.

These are pretty tricky unless your prof has actually shown you how to do this sort of thing. I'll do 3, and you figure out how to do 5.
This works because 4 == 1 mod 3:
static boolean isDivisibleBy3(int n)
{
while(n<0 || n>3) {
n = (n&3) + (n>>2);
}
return (n==3 || n==0)
}
n&3 gets the lower two bits. (n>>2) gets the rest of the bits and divides by 4. Because 4 == 1 mod 3, dividing by 4 doesn't change the remainder mod 3. Then we add them back together and get a smaller number with the same remainder as the one we started with.
Repeat until we get a number less than 4. At that point it's not going to get any smaller.
There are faster ways to do this, but this way is the easiest to understand.

Related

Bitwise alternative modulo gives different results

I'm looking for an alternative for modulo, for Java. The reason is performance.
I have to run a script which loops some time and performs a modulo calculation each loop. Now I read on quite some websites there is a bitwise solution for this, but it gives different results in case of 1 % 3.
1 % 3; // results in 1
1 & (3-1); // results in 0
Can somebody explain this? Most calculations went fine, but this is one combination I found which does not give equal results.
For positive integers, i & (n-1) is equivalent to i % n if n is a power of 2. It doesn't work for all numbers. Otherwise we'd all be doing it the fast way all of the time.

Sum to determine the largest multiple of 5 under 1,000

I am currently trying to get a feature working in a Java application I am making, however I'm uncertain how to implement this in a single line.
I know that I could do something along the lines of (not exactly, but roughly):
while(i<995){
i=i+5
}
However I am eager to implement this all into one line, such as in a single
static int highestMult = *the equation*
I would not be using this specifically for the highest multiple of 5 in 1,000, however upon my own research I could not find a desired solution for this specific case, therefore this is an example.
The examples I have previously found all, generally, relate to finding only a highest multiple, not putting together the highest multiple, and a limit.
If this is not knowledge from the back of your head, it'd also be a great help just to understand the logic behind how you came up with the solution, it could save me being stuck on similar issues in the future.
Thanks,
If c is the under number (1000 in your case), and m the multiple (5 in your case), then
((c - 1) / m) * m
is one way. (Note to purists: you don't actually need the outer parentheses but I include them for clarity).
Here I'm exploiting integer arithmetic to force the truncation of ((c - 1) / m) to the flooring integer. Multiplication of this result by m means the final value is a multiple of m. Make sure that c and m are integral types or this will not work (unless you cast explicitly which is not as elegant).
This is undefined for c < 1 and m < 1
try:
int number=5;
int limit=999;
int i=limit-(limit%number);
where 999 is limit - 1
% is reminder
(999%5)=4
if we remove the reminder from limit, we will got it:
999-4=995
we could use limit=1000, but result could be 1000 too
reminder is very useful thing for programming :D
defined for number > 0 and limit >=0

implementing a patricia trie in java

I'm trying to rewrite a c++ patricia trie in java.
The c++ code is from here
full source code
I'm a bit stuck.
So here's my understanding:
#define ZEROTAB_SIZE 256
head->key = (char*)calloc(ZEROTAB_SIZE, 1);
we create an array of 256 bits for the key, so we can have a string with a maximum length of 32 characters and every character is represented with 8 bits. Can i implement this with a char array in java?
template <class T>
int PatriciaTrie<T>::bit_get(PatriciaTrieKey bit_stream, int n) {
if (n < 0) return 2; // "pseudo-bit" with a value of 2.
int k = (n & 0x7);
return ( (*(bit_stream + (n >> 3))) >> k) & 0x1;
}
k gets the last 7 bits of n, we move to the n/8 character of the string (not exactly n/8 since shifting to the right would remove anything lower than 8 to zero) then we shift the value of bit_stream[n>>3] by k and then we get last bit. if i use arrays in java could i rewrite this as
return (bit_stream[n>>3] >> k) & 0x1;
?
template <class T>
int PatriciaTrie<T>::bit_first_different(PatriciaTrieKey k1, PatriciaTrieKey k2) {
if (!k1 || !k2)
return 0; // First bit is different!
int n = 0;
int d = 0;
while ( (k1[n] == k2[n]) &&
(k1[n] != 0) &&
(k2[n] != 0) )
n++;
while (bit_get(&k1[n], d) == bit_get(&k2[n], d))
d++;
return ((n << 3) + d);
}
now this is where it gets confusing, the first part until the second while loop looks clear enough, loop and check how many bits are equal and non zero, but the i'm not sure what the second loop is doing, we take the address of the two keys and check the first bits if they're equal and if they are we check again until we find unequal bits?
Mainly i'm not sure how the address of the key is used here, but i might be confused on bit shifting in bit_get class too.
I want to do a comparison between there trie in c++ and java for my java class and i want to keep the implementations as similar as possible.
I'm not familiar with this data structure, but there are some problems with your understanding of this code.
First, calloc allocates 256 bytes, not bits. new byte[256] Would be comparable in java.
Second, n & 0x7 gets three bits of n, not seven. A clearer way to write this would be n/8 and n%8 instead of n>>3 and n & 7, but the bitwise operations might be slightly faster if your compiler is stupid.
You are correct that (bit_stream[n>>3]>>k) & 1 is the same.
Now, the first loop in bit_first_different loops over bytes, not bits. The check for 0 is to prevent running off the end of the keys. Once that loop terminates, n refers to the first differing byte. The second loop is then looking for which bit is different.
Note that if the two keys are not different, then the second loop may run off the end of the keys, potentially causing a segmentation fault.
Now, the & is taking the address of k1[n] because the bit_get function is expecting a pointer to a character...this passes in the nth element of the bit stream. After the loop, d is the offset of the first different bit of k[n].
Finally the code combines n (which byte?) With d (which bit in that byte?) to give the bit. Again I would advocate 8*n+d for clarity, but that's a matter of taste.
Can i implement this with a char array in java?
My java is a bit rusty but I believe char is signed in java which means that >> won't do what you expect it to. That's because shifting a signed number will not shift the sign bit so what you really want is the >>> operator or just use the byte type which is unsigned. I have a feeling that this is all kinds of wrong so please double-check.
return (bit_stream[n>>3] >> k) & 0x1;
In C or C++, *(array + k) is just another way to write array[k] so your translation looks correct. As for the interpretation, bit_stream[n>>3] essentially fetches the byte in which the desired bit is located. >> k Moves the desired bit in the least-significant bit position. Finally, we remove all the bits we're not interested in by masking them out with & 0x1. This leaves us with a value of either 0 or 1 depending on whether the bit was set or not.
What the final function does is compare 2 bit strings and returns the bit position where the 2 strings first differ. The first loop is essentially an optimized version of the second loop where instead of doing a bit by bit comparaison, it checks whole bytes instead.
In other words, it first loops over every bytes and find the first 2 that differ. It then takes those 2 differing bytes and loops over them until it finds the first 2 bit that differ. Note that the bit_get function is never going to receive an n greater 7 in this scenario because we know there's a difference somewhere in the byte. The final bit position is then constructed from the the result of both loops like so: (number_of_equal_bytes * 8) + number_of_equal_bits).

library for integer factorization in java or scala

There are a lot of questions about how to implement factorization, however for production use, I would rather use an open source library to get something efficient and well tested right away.
The method I am looking for looks like this:
static int[] getPrimeFactors(int n)
it would return {2,2,3} for n=12
A library may also have an overload for handling long or even BigInteger types
The question is not about a particular application, it is about having a library which handles well this problem. Many people argue that different implementations are needed depending on the range of the numbers, in this regard, I would expect that the library select the most reasonable method at runtime.
By efficient I don't mean "world fastest" (I would not work on the JVM for that...), I just mean dealing with int and long range within a second rather than a hour.
It depends what you want to do. If your needs are modest (say, you want to solve Project Euler problems), a simple implementation of Pollard's rho algorithm will find factors up to ten or twelve digits instantly; if that's what you want, let me know, and I can post some code. If you want a more powerful factoring program that's written in Java, you can look at the source code behind Dario Alpern's applet; I don't know about a test suite, and it's really not designed with an open api, but it does have lots of users and is well tested. Most of the heavy-duty open-source factoring programs are written in C or C++ and use the GMP big-integer library, but you may be able to access them via your language's foreign function interface; look for names like gmp-ecm, msieve, pari or yafu. If those don't satisfy you, a good place to ask for more help is the Mersenne Forum.
If you want to solve your problem, rather than get what you are asking for, you want a table. You can precompute it using silly slow methods, store it, and then look up the factors for any number in microseconds. In particular, you want a table where the smallest factor is listed in an index corresponding to the number--much more memory efficient if you use trial division to remove a few of the smallest primes--and then walk your way down the table until you hit a 1 (meaning no more divisors; what you have left is prime). This will take only two bytes per table entry, which means you can store everything on any modern machine more hefty than a smartphone.
I can demonstrate how to create this if you're interested, and show how to check that it is correct with greater reliability than you could hope to achieve with an active community and unit tests of a complex algorithm (unless you ran the algorithm to generate this table and verified that it was all ok).
I need them for testing if a polynomial is primitive or not.
This is faster than trying to find the factors of all the numbers.
public static boolean gcdIsOne(int[] nums) {
int smallest = Integer.MAX_VALUE;
for (int num : nums) {
if (num > 0 && smallest < num)
smallest = num;
}
OUTER:
for (int i = 2; i * i <= smallest; i = (i == 2 ? 3 : i + 2)) {
for (int num : nums) {
if (num % i != 0)
continue OUTER;
}
return false;
}
return true;
}
I tried this function in scala. Here is my result:
def getPrimeFactores(i: Int) = {
def loop(i: Int, mod: Int, primes: List[Int]): List[Int] = {
if (i < 2) primes // might be i == 1 as well and means we are done
else {
if (i % mod == 0) loop(i / mod, mod, mod :: primes)
else loop(i, mod + 1, primes)
}
}
loop(i, 2, Nil).reverse
}
I tried it to be as much functional as possible.
if (i % mod == 0) loop(i / mod, mod, mod :: primes) checks if we found a divisor. If we did we add it to primes and divide i by mod.
If we did not find a new divisor, we just increase the divisor.
loop(i, 2, Nil).reverse initializes the function and orders the result increasingly.

What does this statement mean?

Found it on this website.
holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
I'M asking for the "position & 1 ..."
I've seen this statement several times, but never knew what it means :/ Though I guess its handy to know :P
Thanks!
& is the bitwise AND operator. Basically, (position & 1) is checking whether the least-significant bit of position is 1 or 0, which is a way of checking whether position is odd or even.
For a full run-down of Java operators, see e.g. http://download.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html.
It is a bitwise AND of (the value of) position and 1.
So, if the least significant bit of position is 1 it will return 1, otherwise it returns 0.
The single & sign is a bitwise AND operation. You usually use them to apply a bit-mask. In this case if position's last (least significant) bit is 1 then (position & 1) == 1 will be true since the & 1 will zero everything except the last bit by "and-ing" each bit of 'position' with 1.

Categories