Programming Problems: Advanced Algorithms Flashcards
Setting the least significant bit to zero
unsigned clear_last_bit(unsigned x) {
return x & (x - 1);
}
Lowest bit set - retain only the lowest set bit
(10100 -> 00100)
unsigned lowest_set_bit(unsigned x) {
return x & ~(x-1);
}
Counting the number of bits in a number
While the number is not zero clear the least significant bit.
Clearing least significant bit: x & (x-1)
Folding over
(Setting all bits after the MSB to 1)
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
Isolate the highest bit
x = foldOver(x); // makes all bits 1 after the highest bit
result = x & ~(x>>1)
Rounded log2 of an integer
x = x-1 // x must be unsigned int
x = foldOver(x)
x=x+1
result = 0;
while (x!=0) {
x>>=1; result++;
}
Next power of 2 that is larger than the input
result = foldOver(x) + 1
Reverse the bits in a 32bit integer
(using O(logn) time complexity)
x = ((x & 0xffff0000) >> 16) | ((x & 0x0000ffff) << 16);
x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
x = ((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4);
x = ((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2);
x = ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1);
return x;
Int multiplication using bitwise operators
int multiply(int x, int y) {
int product = 0;
while (y) {
product += x << log_x(lowest_set_bit(y));
y = clear_last_bit(y);
}
return product;
General fibonacci expression
F(0)=0; F(1)=1;
F(n)=F(n-1)+F(n-2);
Recursive fibonacci algorithm
if (n==0) return 0;
if (n==1) return 1;
return fib(n-1)+fib(n-2);
What is the runtime of the reecursive fibonacci algorithm?
Exponential function of the input.
Iterative fibonacci algorithm
if (n==0) return 0; if (n==1) return 1;
int cur = 0; int trailing = 1;
for (int i=0;i<n></n>
<p> int temp = cur;</p>
<p> cur = cur + trailing;</p>
<p> trailing = temp;}</p>
<p>return cur;</p>
</n>
Fibonacci with tail recursion
int fiboTail(int n, int fib1, int fib2) {
if (1==n) return fib1;
return fibTail(n-1,fib2,fib1+fib2);
}
int fibo(int n) {
if (0==n) return 0;
return fiboTail(n,0,1);
}
Closed formula for calculating the nth fibonacci element