Boolean Parenthesization Algorithm - algorithm

I'm working on the following algorithm out of Cracking The Coding Interview:
Given a boolean expression containing the symbols {true, false, and,
or, xor}, count the number of ways to parenthesize the expression such
that it evaluates to true.
The author details a recursive solution of placing parenthesis at each operator char. So for example, if expression is 1^0^0|1 then placing at char = 1 would be (1)^(0^0|1).
She does this for every operator char i from 1 to n, where the two expressions are from 0 to i and i + 1 to n, and then calls the recursive function on each substring.
Here's what I don't understand. For example, 1^(0^0)|1 this expression is excluded from this process. Why is that? Isn't this also important to be considered?

1 ^ (0 ^ 0) | 1 is the same as (1 ^ (0 ^ 0)) | (1).
Since you mentioned that the parantheses are inserted recursively, nothing is left out:
1 ^ 0 ^ 0 | 1
|
+--(1) ^ (0 ^ 0 | 1)
| +--(1) ^ ((0 ^ 0) | 1)
| +--(1) ^ (0 ^ (0 | 1))
|
+--(1 ^ 0) ^ (0 | 1)
|
+--(1 ^ 0 ^ 0) | (1)
+--((1 ^ 0) ^ 0) | (1)
+--(1 ^ (0 ^ 0)) | (1) ← here it is

Related

How can I modify bit in position in Go?

I tried to modify bit at a certain position, but ran into a problem.
For example I have 1000000001, how can I modify it to 0000000001?
You can apply a bitmask to only keep the bits you are interested in.
In this case if you only want the last bit, you apply the bitmask 0b0000000001
https://go.dev/play/p/RNQEcON7sw1
// 'x' is your value
x := 0b1000000001
// Make the bitmask
mask := 0b0000000001
// Apply the bitmask with bitwise AND
output := x&mask
fmt.Println("This value == 1: ", output)
Explaination
& is a bitwise operator for "AND". Which means it goes through both values bit by bit and sets the resulting bit to 1 if and only if both input bits are 1. I included a truth table for the AND operator below.
+-----------+----------+--------------+
| Input Bit | Mask Bit | Input & Mask |
+-----------+----------+--------------+
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
+-----------+----------+--------------+
Because my mask function only has a 1 in the last position, only the last position of the original input is kept. All preceding bits will always be 0.
Construct a mask that has a one in every place you want to manipulate
Use bitwise OR to set bits.
Use bitwise AND with the inverse mask to clear bits.
Use XOR to toggle a bits
package main
import "fmt"
func main() {
k := 3 // manipulate the 3rd bit ...
mask := uint8(1) << (k - 1) // ... using 0b00000100 as a mask
var n uint8 = 0b10101010
fmt.Printf("0b%08b\n", n) // 0b10101010
// set kth bit
n |= mask
fmt.Printf("0b%08b\n", n) // 0b10101110
// clear kth bit
n &^= mask // &^ is Go's AND NOT operator
fmt.Printf("0b%08b\n", n) // 0b10101010
// toggle kth bit
n ^= mask
fmt.Printf("0b%08b\n", n) // 0b10101110
}
func test() {
i := 1 << 9 //1000000000
i = i | (1 << 8) //1000000000 | 0100000000 == 1100000000
i = i | (1 << 7) //1100000000 | 0010000000 == 1110000000
i = i | (1 << 0) //1110000000 | 0000000001 == 1110000001
fmt.Printf("BEFORE: %010b\n", i) // 1110000001
i = i & ((1 << 9) - 1) // 1110000001 & ((1000000000) - 1) == 1110000001 & (0111111111) == 0110000001
fmt.Printf("AFTER: %010b\n", i) // 0110000001
}

How does middle rounds of AES encryption work in Go runtime?

I learn how AES`s implementation work in Go and I do not understand how middle rounds work while encrypt block in https://github.com/golang/go/blob/master/src/crypto/aes/block.go:
// Middle rounds shuffle using tables.
// Number of rounds is set by length of expanded key.
nr := len(xk)/4 - 2 // - 2: one above, one more below
k := 4
for r := 0; r < nr; r++ {
t0 = xk[k+0] ^ te0[uint8(s0>>24)] ^ te1[uint8(s1>>16)] ^ te2[uint8(s2>>8)] ^ te3[uint8(s3)]
t1 = xk[k+1] ^ te0[uint8(s1>>24)] ^ te1[uint8(s2>>16)] ^ te2[uint8(s3>>8)] ^ te3[uint8(s0)]
t2 = xk[k+2] ^ te0[uint8(s2>>24)] ^ te1[uint8(s3>>16)] ^ te2[uint8(s0>>8)] ^ te3[uint8(s1)]
t3 = xk[k+3] ^ te0[uint8(s3>>24)] ^ te1[uint8(s0>>16)] ^ te2[uint8(s1>>8)] ^ te3[uint8(s2)]
k += 4
s0, s1, s2, s3 = t0, t1, t2, t3
}
I understand that this code do SybButes, ShiftRows, MixColumns and AddRoundKey of AES, but I do not understand how this code do it by using
"te0", "te1", "te2", "te3" arrays. It's precomputed arrays which are defined in https://github.com/golang/go/blob/master/src/crypto/aes/const.go.
May someone explain to me how these arrays was precomputed? Thank you so much for you help.
I have found an answer to my question in:
https://crypto.stackexchange.com/questions/19175/efficient-aes-use-of-t-tables
Generating AES (AES-256) Lookup Tables
https://golang.org/src/crypto/aes/aes_test.go

Find the closest integer with same weight O(1)

I am solving this problem:
The count of ones in binary representation of integer number is called the weight of that number. The following algorithm finds the closest integer with the same weight. For example, for 123 (0111 1011)₂, the closest integer number is 125 (0111 1101)₂.
The solution for O(n)
where n is the width of the input number is by swapping the positions of the first pair of consecutive bits that differ.
Could someone give me some hints for solving in it in O(1) runtime and space ?
Thanks
As already commented by ajayv this cannot really be done in O(1) as the answer always depends on the number of bits the input has. However, if we interpret the O(1) to mean that we have as an input some primitive integer data and all the logic and arithmetic operations we perform on that integer are O(1) (no loops over the bits), the problem can be solved in constant time. Of course, if we changed from 32bit integer to 64bit integer the running time would increase as the arithmetic operations would take longer on hardware.
One possible solution is to use following functions. The first gives you a number where only the lowest set bit of x is set
int lowestBitSet(int x){
( x & ~(x-1) )
}
and the second the lowest bit not set
int lowestBitNotSet(int x){
return ~x & (x+1);
}
If you work few examples of these on paper you see how they work.
Now you can find the bits you need to change using these two functions and then use the algorithm you already described.
A c++ implementation (not checking for cases where there are no answer)
unsigned int closestInt(unsigned int x){
unsigned int ns=lowestBitNotSet(x);
unsigned int s=lowestBitSet(x);
if (ns>s){
x|=ns;
x^=ns>>1;
}
else{
x^=s;
x|=s>>1;
}
return x;
}
To solve this problem in O(1) time complexity it can be considered that there are two main cases:
1) When LSB is '0':
In this case, the first '1' must be shifted with one position to the right.
Input : "10001000"
Out ::: "10000100"
2) When LSB is '1':
In this case the first '0' must be set to '1', and first '1' must be set to '0'.
Input : "10000111"
Out ::: "10001110"
The next method in Java represents one solution.
private static void findClosestInteger(String word) { // ex: word = "10001000"
System.out.println(word); // Print initial binary format of the number
int x = Integer.parseInt(word, 2); // Convert String to int
if((x & 1) == 0) { // Evaluates LSB value
// Case when LSB = '0':
// Input: x = 10001000
int firstOne = x & ~(x -1); // get first '1' position (from right to left)
// firstOne = 00001000
x = x & (x - 1); // set first '1' to '0'
// x = 10000000
x = x | (firstOne >> 1); // "shift" first '1' with one position to right
// x = 10000100
} else {
// Case when LSB = '1':
// Input: x = 10000111
int firstZero = ~x & ~(~x - 1); // get first '0' position (from right to left)
// firstZero = 00001000
x = x & (~1); // set first '1', which is the LSB, to '0'
// x = 10000110
x = x | firstZero; // set first '0' to '1'
// x = 10001110
}
for(int i = word.length() - 1; i > -1 ; i--) { // print the closest integer with same weight
System.out.print("" + ( ( (x & 1 << i) != 0) ? 1 : 0) );
}
}
The problem can be viewed as "which differing bits to swap in a bit representation of a number, so that the resultant number is closest to the original?"
So, if we we're to swap bits at indices k1 & k2, with k2 > k1, the difference between the numbers would be 2^k2 - 2^k1. Our goal is to minimize this difference. Assuming that the bit representation is not all 0s or all 1s, a simple observation yields that the difference would be least if we kept |k2 - k1| as minimum. The minimum value can be 1. So, if we're able to find two consecutive different bits, starting from the least significant bit (index = 0), our job is done.
The case where bits starting from Least Significant Bit to the right most set bit are all 1s
k2
|
7 6 5 4 3 2 1 0
---------------
n: 1 1 1 0 1 0 1 1
rightmostSetBit: 0 0 0 0 0 0 0 1
rightmostNotSetBit: 0 0 0 0 0 1 0 0 rightmostNotSetBit > rightmostSetBit so,
difference: 0 0 0 0 0 0 1 0 i.e. rightmostNotSetBit - (rightmostNotSetBit >> 1):
---------------
n + difference: 1 1 1 0 1 1 0 1
The case where bits starting from Least Significant Bit to the right most set bit are all 0s
k2
|
7 6 5 4 3 2 1 0
---------------
n: 1 1 1 0 1 1 0 0
rightmostSetBit: 0 0 0 0 0 1 0 0
rightmostNotSetBit: 0 0 0 0 0 0 0 1 rightmostSetBit > rightmostNotSetBit so,
difference: 0 0 0 0 0 0 1 0 i.e. rightmostSetBit -(rightmostSetBit>> 1)
---------------
n - difference: 1 1 1 0 1 0 1 0
The edge case, of course the situation where we have all 0s or all 1s.
public static long closestToWeight(long n){
if(n <= 0 /* If all 0s */ || (n+1) == Integer.MIN_VALUE /* n is MAX_INT */)
return -1;
long neg = ~n;
long rightmostSetBit = n&~(n-1);
long rightmostNotSetBit = neg&~(neg-1);
if(rightmostNotSetBit > rightmostSetBit){
return (n + (rightmostNotSetBit - (rightmostNotSetBit >> 1)));
}
return (n - (rightmostSetBit - (rightmostSetBit >> 1)));
}
Attempted the problem in Python. Can be viewed as a translation of Ari's solution with the edge case handled:
def closest_int_same_bit_count(x):
# if all bits of x are 0 or 1, there can't be an answer
if x & sys.maxsize in {sys.maxsize, 0}:
raise ValueError("All bits are 0 or 1")
rightmost_set_bit = x & ~(x - 1)
next_un_set_bit = ~x & (x + 1)
if next_un_set_bit > rightmost_set_bit:
# 0 shifted to the right e.g 0111 -> 1011
x ^= next_un_set_bit | next_un_set_bit >> 1
else:
# 1 shifted to the right 1000 -> 0100
x ^= rightmost_set_bit | rightmost_set_bit >> 1
return x
Similarly jigsawmnc's solution is provided below:
def closest_int_same_bit_count(x):
# if all bits of x are 0 or 1, there can't be an answer
if x & sys.maxsize in {sys.maxsize, 0}:
raise ValueError("All bits are 0 or 1")
rightmost_set_bit = x & ~(x - 1)
next_un_set_bit = ~x & (x + 1)
if next_un_set_bit > rightmost_set_bit:
# 0 shifted to the right e.g 0111 -> 1011
x += next_un_set_bit - (next_un_set_bit >> 1)
else:
# 1 shifted to the right 1000 -> 0100
x -= rightmost_set_bit - (rightmost_set_bit >> 1)
return x
Java Solution:
//Swap the two rightmost consecutive bits that are different
for (int i = 0; i < 64; i++) {
if ((((x >> i) & 1) ^ ((x >> (i+1)) & 1)) == 1) {
// then swap them or flip their bits
int mask = (1 << i) | (1 << i + 1);
x = x ^ mask;
System.out.println("x = " + x);
return;
}
}
static void findClosestIntWithSameWeight(uint x)
{
uint xWithfirstBitSettoZero = x & (x - 1);
uint xWithOnlyfirstbitSet = x & ~(x - 1);
uint xWithNextTofirstBitSet = xWithOnlyfirstbitSet >> 1;
uint closestWeightNum = xWithfirstBitSettoZero | xWithNextTofirstBitSet;
Console.WriteLine("Closet Weight for {0} is {1}", x, closestWeightNum);
}
Code in python:
def closest_int_same_bit_count(x):
if (x & 1) != ((x >> 1) & 1):
return x ^ 0x3
diff = x ^ (x >> 1)
rbs = diff & ~(diff - 1)
i = int(math.log(rbs, 2))
return x ^ (1 << i | 1 << i + 1)
A great explanation of this problem can be found on question 4.4 in EPI.
(Elements of Programming Interviews)
Another place would be this link on geeksforgeeks.org if you don't own the book.
(Time complexity may be wrong on this link)
Two things you should keep in mind here is (Hint if you're trying to solve this for yourself):
You can use x & (x - 1) to clear the lowest set-bit (not to get confused with LSB - least significant bit)
You can use x & ~(x - 1) to get/extract the lowest set bit
If you know the O(n) solution you know that we need to find the index of the first bit that differs from LSB.
If you don't know what the LBS is:
0000 0000
^ // it's bit all the way to the right of a binary string.
Take the base two number 1011 1000 (184 in decimal)
The first bit that differs from LSB:
1011 1000
^ // this one
We'll record this as K1 = 0000 1000
Then we need to swap it with the very next bit to the right:
0000 1000
^ // this one
We'll record this as K2 = 0000 0100
Bitwise OR K1 and K2 together and you'll get a mask
mask = K1 | k2 // 0000 1000 | 0000 0100 -> 0000 1100
Bitwise XOR the mask with the original number and you'll have the correct output/swap
number ^ mask // 1011 1000 ^ 0000 1100 -> 1011 0100
Now before we pull everything together we have to consider that fact that the LSB could be 0001, and so could a bunch of bits after that 1000 1111. So we have to deal with the two cases of the first bit that differs from the LSB; it may be a 1 or 0.
First we have a conditional that test the LSB to be 1 or 0: x & 1
IF 1 return x XORed with the return of a helper function
This helper function has a second argument which its value depends on whether the condition is true or not. func(x, 0xFFFFFFFF) // if true // 0xFFFFFFFF 64 bit word with all bits set to 1
Otherwise we'll skip the if statement and return a similar expression but with a different value provided to the second argument.
return x XORed with func(x, 0x00000000) // 64 bit word with all bits set to 0. You could alternatively just pass 0 but I did this for consistency
Our helper function returns a mask that we are going to XOR with the original number to get our output.
It takes two arguments, our original number and a mask, used in this expression:
(x ^ mask) & ~((x ^ mask) - 1)
which gives us a new number with the bit at index K1 always set to 1.
It then shifts that bit 1 to the right (i.e index K2) then ORs it with itself to create our final mask
0000 1000 >> 1 -> 0000 0100 | 0001 0000 -> 0000 1100
This all implemented in C++ looks like:
unsigned long long int closestIntSameBitCount(unsigned long long int n)
{
if (n & 1)
return n ^= getSwapMask(n, 0xFFFFFFFF);
return n ^= getSwapMask(n, 0x00000000);
}
// Helper function
unsigned long long int getSwapMask(unsigned long long int n, unsigned long long int mask)
{
unsigned long long int swapBitMask = (n ^ mask) & ~((n ^ mask) - 1);
return swapBitMask | (swapBitMask >> 1);
}
Keep note of the expression (x ^ mask) & ~((x ^ mask) - 1)
I'll now run through this code with my example 1011 1000:
// start of closestIntSameBitCount
if (0) // 1011 1000 & 1 -> 0000 0000
// start of getSwapMask
getSwapMask(1011 1000, 0x00000000)
swapBitMask = (x ^ mask) & ~1011 0111 // ((x ^ mask) - 1) = 1011 1000 ^ .... 0000 0000 -> 1011 1000 - 1 -> 1011 0111
swapBitMask = (x ^ mask) & 0100 1000 // ~1011 0111 -> 0100 1000
swapBitMask = 1011 1000 & 0100 1000 // (x ^ mask) = 1011 1000 ^ .... 0000 0000 -> 1011 1000
swapBitMask = 0000 1000 // 1011 1000 & 0100 1000 -> 0000 1000
return swapBitMask | 0000 0100 // (swapBitMask >> 1) = 0000 1000 >> 1 -> 0000 0100
return 0000 1100 // 0000 1000 | 0000 0100 -> 0000 11000
// end of getSwapMask
return 1011 0100 // 1011 1000 ^ 0000 11000 -> 1011 0100
// end of closestIntSameBitCount
Here is a full running example if you would like compile and run it your self:
#include <iostream>
#include <stdio.h>
#include <bitset>
unsigned long long int closestIntSameBitCount(unsigned long long int n);
unsigned long long int getSwapMask(unsigned long long int n, unsigned long long int mask);
int main()
{
unsigned long long int number;
printf("Pick a number: ");
std::cin >> number;
std::bitset<64> a(number);
std::bitset<64> b(closestIntSameBitCount(number));
std::cout << a
<< "\n"
<< b
<< std::endl;
}
unsigned long long int closestIntSameBitCount(unsigned long long int n)
{
if (n & 1)
return n ^= getSwapMask(n, 0xFFFFFFFF);
return n ^= getSwapMask(n, 0x00000000);
}
// Helper function
unsigned long long int getSwapMask(unsigned long long int n, unsigned long long int mask)
{
unsigned long long int swapBitMask = (n ^ mask) & ~((n ^ mask) - 1);
return swapBitMask | (swapBitMask >> 1);
}
This was my solution to the problem. I guess #jigsawmnc explains pretty well why we need to have |k2 -k1| to a minimum. So in order to find the closest integer, with the same weight, we would want to find the location where consecutive bits are flipped and then flip them again to get the answer. In order to do that we can shift the number 1 unit. Take the XOR with the same number. This will set bits at all locations where there is a flip. Find the least significant bit for the XOR. This will give you the smallest location to flip. Create a mask for the location and next bit. Take an XOR and that should be the answer. This won't work, if the digits are all 0 or all 1
Here is the code for it.
def variant_closest_int(x: int) -> int:
if x == 0 or ~x == 0:
raise ValueError('All bits are 0 or 1')
x_ = x >> 1
lsb = x ^ x_
mask_ = lsb & ~(lsb - 1)
mask = mask_ | (mask_ << 1)
return x ^ mask
My solution, takes advantage of the parity of the integer. I think the way I got the LSB masks can be simplified
def next_weighted_int(x):
if x % 2 == 0:
lsb_mask = ( ((x - 1) ^ x) >> 1 ) + 1 # Gets a mask for the first 1
x ^= lsb_mask
x |= (lsb_mask >> 1)
return x
lsb_mask = ((x ^ (x + 1)) >> 1 ) + 1 # Gets a mask for the first 0
x |= lsb_mask
x ^= (lsb_mask >> 1)
return x
Just sharing my python solution for this problem:
def same closest_int_same_bit_count(a):
x = a + (a & 1) # change last bit to 0
bit = (x & ~(x-1)) # get last set bit
return a ^ (bit | bit >> 1) # swap set bit with unset bit
func findClosestIntegerWithTheSameWeight2(x int) int {
rightMost0 := ^x & (x + 1)
rightMost1 := x & (-x)
if rightMost0 > 1 {
return (x ^ rightMost0) ^ (rightMost0 >> 1)
} else {
return (x ^ rightMost1) ^ (rightMost1 >> 1)
}
}

Strange multiplication behavior in Guile Scheme interpreter

I was practicing Scheme in Guile 1.8.8 interpreter on OS X. I noticed something interesting.
Here's expt function which is basically does exponentiation expt(b,n) = b^n :
(define (square x) (* x x))
(define (even? x) (= (remainder x 2) 0))
(define (expt b n)
(cond ((= n 0) 1)
((even? n) (square (expt b (/ n 2))))
(else (* b (expt b (- n 1))))
))
If I try it with some inputs
> (expt 2 10)
1024
> (expt 2 63)
9223372036854775808
Here comes the strange part:
> (expt 2 64)
0
More strangely, until n=488 it stays at 0:
> (expt 2 487)
0
> (expt 2 488)
79916762888089401123.....
> (expt 2 1000)
1071508607186267320948425049060....
> (expt 2 10000)
0
When I try this code with repl.it online interpreter, it works as expected. So what the hell is wrong with Guile?
(Note: On some dialects, remainder function is called as mod.)
I recently fixed this bug in Guile 2.0. The bug came into existence when C compilers started optimizing out overflow checks, on the theory that if a signed integer overflow occurs then the behavior is unspecified and thus the compiler can do whatever it likes.
I could reproduce the problem with guile 2.0.6 on OS X. It boils down to:
> (* 4294967296 4294967296)
$1 = 0
My guess is that guile uses the native int type to store small numbers, and then switches to a bignums, backed by GNU MP when the native ints are too small. Maybe in that particular case, the check fails, and the computation overflows the native int.
Interestingly, the following loop shows that squaring powers of two between 2^32 and 2^60 results in 0:
(let loop
((x 1)
(exp 0))
(format #t "(2^~s) ^ 2 = ~s\n" exp (* x x))
(if (< exp 100)
(loop (* 2 x) (+ 1 exp))))
Results in:
(2^0) ^ 2 = 1
(2^1) ^ 2 = 4
(2^2) ^ 2 = 16
(2^3) ^ 2 = 64
(2^4) ^ 2 = 256
(2^5) ^ 2 = 1024
(2^6) ^ 2 = 4096
(2^7) ^ 2 = 16384
(2^8) ^ 2 = 65536
(2^9) ^ 2 = 262144
(2^10) ^ 2 = 1048576
(2^11) ^ 2 = 4194304
(2^12) ^ 2 = 16777216
(2^13) ^ 2 = 67108864
(2^14) ^ 2 = 268435456
(2^15) ^ 2 = 1073741824
(2^16) ^ 2 = 4294967296
(2^17) ^ 2 = 17179869184
(2^18) ^ 2 = 68719476736
(2^19) ^ 2 = 274877906944
(2^20) ^ 2 = 1099511627776
(2^21) ^ 2 = 4398046511104
(2^22) ^ 2 = 17592186044416
(2^23) ^ 2 = 70368744177664
(2^24) ^ 2 = 281474976710656
(2^25) ^ 2 = 1125899906842624
(2^26) ^ 2 = 4503599627370496
(2^27) ^ 2 = 18014398509481984
(2^28) ^ 2 = 72057594037927936
(2^29) ^ 2 = 288230376151711744
(2^30) ^ 2 = 1152921504606846976
(2^31) ^ 2 = 4611686018427387904
(2^32) ^ 2 = 0
(2^33) ^ 2 = 0
(2^34) ^ 2 = 0
(2^35) ^ 2 = 0
(2^36) ^ 2 = 0
(2^37) ^ 2 = 0
(2^38) ^ 2 = 0
(2^39) ^ 2 = 0
(2^40) ^ 2 = 0
(2^41) ^ 2 = 0
(2^42) ^ 2 = 0
(2^43) ^ 2 = 0
(2^44) ^ 2 = 0
(2^45) ^ 2 = 0
(2^46) ^ 2 = 0
(2^47) ^ 2 = 0
(2^48) ^ 2 = 0
(2^49) ^ 2 = 0
(2^50) ^ 2 = 0
(2^51) ^ 2 = 0
(2^52) ^ 2 = 0
(2^53) ^ 2 = 0
(2^54) ^ 2 = 0
(2^55) ^ 2 = 0
(2^56) ^ 2 = 0
(2^57) ^ 2 = 0
(2^58) ^ 2 = 0
(2^59) ^ 2 = 0
(2^60) ^ 2 = 0
(2^61) ^ 2 = 5316911983139663491615228241121378304
(2^62) ^ 2 = 21267647932558653966460912964485513216
(2^63) ^ 2 = 85070591730234615865843651857942052864
(2^64) ^ 2 = 340282366920938463463374607431768211456
(2^65) ^ 2 = 1361129467683753853853498429727072845824
(2^66) ^ 2 = 5444517870735015415413993718908291383296
(2^67) ^ 2 = 21778071482940061661655974875633165533184
(2^68) ^ 2 = 87112285931760246646623899502532662132736
(2^69) ^ 2 = 348449143727040986586495598010130648530944
(2^70) ^ 2 = 1393796574908163946345982392040522594123776
(2^71) ^ 2 = 5575186299632655785383929568162090376495104
(2^72) ^ 2 = 22300745198530623141535718272648361505980416
(2^73) ^ 2 = 89202980794122492566142873090593446023921664
(2^74) ^ 2 = 356811923176489970264571492362373784095686656
(2^75) ^ 2 = 1427247692705959881058285969449495136382746624
(2^76) ^ 2 = 5708990770823839524233143877797980545530986496
(2^77) ^ 2 = 22835963083295358096932575511191922182123945984
(2^78) ^ 2 = 91343852333181432387730302044767688728495783936
(2^79) ^ 2 = 365375409332725729550921208179070754913983135744
(2^80) ^ 2 = 1461501637330902918203684832716283019655932542976
(2^81) ^ 2 = 5846006549323611672814739330865132078623730171904
(2^82) ^ 2 = 23384026197294446691258957323460528314494920687616
(2^83) ^ 2 = 93536104789177786765035829293842113257979682750464
(2^84) ^ 2 = 374144419156711147060143317175368453031918731001856
(2^85) ^ 2 = 1496577676626844588240573268701473812127674924007424
(2^86) ^ 2 = 5986310706507378352962293074805895248510699696029696
(2^87) ^ 2 = 23945242826029513411849172299223580994042798784118784
(2^88) ^ 2 = 95780971304118053647396689196894323976171195136475136
(2^89) ^ 2 = 383123885216472214589586756787577295904684780545900544
(2^90) ^ 2 = 1532495540865888858358347027150309183618739122183602176
(2^91) ^ 2 = 6129982163463555433433388108601236734474956488734408704
(2^92) ^ 2 = 24519928653854221733733552434404946937899825954937634816
(2^93) ^ 2 = 98079714615416886934934209737619787751599303819750539264
(2^94) ^ 2 = 392318858461667547739736838950479151006397215279002157056
(2^95) ^ 2 = 1569275433846670190958947355801916604025588861116008628224
(2^96) ^ 2 = 6277101735386680763835789423207666416102355444464034512896
(2^97) ^ 2 = 25108406941546723055343157692830665664409421777856138051584
(2^98) ^ 2 = 100433627766186892221372630771322662657637687111424552206336
(2^99) ^ 2 = 401734511064747568885490523085290650630550748445698208825344
(2^100) ^ 2 = 1606938044258990275541962092341162602522202993782792835301376
I wasn't able to reproduce your results running Arch.
Here is a log of my terminal session:
$ uname -r
3.6.10-1-ARCH
$ guile --version
Guile 1.8.8
Copyright (c) 1995, 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation
Guile may be distributed under the terms of the GNU General Public Licence;
certain other uses are permitted as well. For details, see the file
`COPYING', which is included in the Guile distribution.
There is no warranty, to the extent permitted by law.
$ guile
guile> (define (square x) (* x x))
guile> (define (even? x) (= (remainder x 2) 0))
guile> (define (expt b n)
(cond ((= n 0) 1)
((even? n) (square (expt b (/ n 2))))
(else (* b (expt b (- n 1))))))
guile> (expt 2 10)
1024
guile> (expt 2 64)
18446744073709551616
guile> (expt 2 487)
399583814440447005616844445413525287135820562261116307309972090832047582568929999375399181192126972308457847183540047730617340886948900519205142528
guile> (expt 2 488)
799167628880894011233688890827050574271641124522232614619944181664095165137859998750798362384253944616915694367080095461234681773897801038410285056
guile> (expt 2 1000)
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
guile> (expt 2 10000)
19950631168807583848837421626835850838234968318861924548520089498529438830221946631919961684036194597899331129423209124271556491349413781117593785932096323957855730046793794526765246551266059895520550086918193311542508608460618104685509074866089624888090489894838009253941633257850621568309473902556912388065225096643874441046759871626985453222868538161694315775629640762836880760732228535091641476183956381458969463899410840960536267821064621427333394036525565649530603142680234969400335934316651459297773279665775606172582031407994198179607378245683762280037302885487251900834464581454650557929601414833921615734588139257095379769119277800826957735674444123062018757836325502728323789270710373802866393031428133241401624195671690574061419654342324638801248856147305207431992259611796250130992860241708340807605932320161268492288496255841312844061536738951487114256315111089745514203313820202931640957596464756010405845841566072044962867016515061920631004186422275908670900574606417856951911456055068251250406007519842261898059237118054444788072906395242548339221982707404473162376760846613033778706039803413197133493654622700563169937455508241780972810983291314403571877524768509857276937926433221599399876886660808368837838027643282775172273657572744784112294389733810861607423253291974813120197604178281965697475898164531258434135959862784130128185406283476649088690521047580882615823961985770122407044330583075869039319604603404973156583208672105913300903752823415539745394397715257455290510212310947321610753474825740775273986348298498340756937955646638621874569499279016572103701364433135817214311791398222983845847334440270964182851005072927748364550578634501100852987812389473928699540834346158807043959118985815145779177143619698728131459483783202081474982171858011389071228250905826817436220577475921417653715687725614904582904992461028630081535583308130101987675856234343538955409175623400844887526162643568648833519463720377293240094456246923254350400678027273837755376406726898636241037491410966718557050759098100246789880178271925953381282421954028302759408448955014676668389697996886241636313376393903373455801407636741877711055384225739499110186468219696581651485130494222369947714763069155468217682876200362777257723781365331611196811280792669481887201298643660768551639860534602297871557517947385246369446923087894265948217008051120322365496288169035739121368338393591756418733850510970271613915439590991598154654417336311656936031122249937969999226781732358023111862644575299135758175008199839236284615249881088960232244362173771618086357015468484058622329792853875623486556440536962622018963571028812361567512543338303270029097668650568557157505516727518899194129711337690149916181315171544007728650573189557450920330185304847113818315407324053319038462084036421763703911550639789000742853672196280903477974533320468368795868580237952218629120080742819551317948157624448298518461509704888027274721574688131594750409732115080498190455803416826949787141316063210686391511681774304792596709376
guile> (exit)

easy algorithm for using flags

Exists flags defs:
flag1=1
flag2=2
flag3=4
flag4=8
...
flagN=2^(N-1)
flag=flag1+flag2+...+flagN
if flagI not set, it eq 0
i have flag. which method can easily check, is for example flag2 defined?
Answer to your question
What's the range of flag? If it's under 2^64-1, almost every method is okay.
As #taskinoor posted, you should notice that:
flag1 = 000 ... ... 0001
flag2 = 000 ... ... 0010
flag3 = 000 ... ... 0100
In other words,
flag[n] = 1 << (n-1)
So, if you want to check all bits, a for loop and bitwise operation are fast enough to solve you problem. Like This (suppose you could understand C/C++ and flag is less than 2^32, which could be hold by an unsigned int in C/C++):
void check(unsigned int flag)
{
for (int i = 0; i < 32; ++i)
if ((flag & (1 << i)) != 0)
printf("flag%d defined!\n", i+1);
}
It's O(k), which k is the length of the type of flag in binary. For unsigned int, it's O(32) = O(1), almost in constant time.
If you just want to count how many flags defined:
I don't know what's your purpose. If you just want to count how many flags defined and flag is less than 2^64, the following method is awesome(suppose unsigned int as well):
unsigned int count_bit(unsigned int x)
{
x = (x & 0x55555555) + ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F);
x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF);
x = (x & 0x0000FFFF) + ((x >> 16)& 0x0000FFFF);
return x;
}
If you call count_bit(1234567890), it'll return 12.
Let me explain this algorithm.
This algorithm is based on Divide and Conquer Algorithm. Suppose there is a 8bit integer 213(11010101 in binary), the algorithm works like this(each time merge two neighbor blocks):
+-------------------------------+
| 1 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | <- x
| 1 0 | 0 1 | 0 1 | 0 1 | <- first time merge
| 0 0 1 1 | 0 0 1 0 | <- second time merge
| 0 0 0 0 0 1 0 1 | <- third time ( answer = 00000101 = 5)
+-------------------------------+
Note that in each flag only one bit is set to 1, others are 0.
flag1 = 000 ... ... 0001
flag2 = 000 ... ... 0010
flag3 = 000 ... ... 0100
// and like this
So if you do bitwise AND flag & flag2 then the result will be non-zero only if flag2 is defined.
r = flag & flag2;
if r != 0 then flag2 is defined
You can do this with all flags.
Boolean isSet (flags, flagN){
Return (flags & flagN) != 0;
}
Flags being the flag vector, flagN the flag you want to check
It is worth grokking the concept of bitmasks and flags more deeply. You can then use your imagination to represent state efficiently . (Just an example explained below)
First -Define the bitmask : 0x0000001c
What are the binary strings for which when you do an 'and' operation on the mask, you get a non-zero value?
Those are your valid flag values.
Valid flag values for this bitmask: 0x0000001c,0x00000014,0x00000018,0x00000004,0x00000008,etc ..
So, in your application if you can do the following:
flagvariable |= flagvalue1 ->Enable a particular flag.
if( flagvariable & maskvalue) :Check if a mask is enabled :
Then the different cases you would need to check :
if(flagvariable &maskvalue ==flagvalue1) { do something}
else
if(flagvariable &maskvalue ==flagvalue2) {do something else}
flagvariable &= `flagvalue1 : Clear the flag
To be more clear about flags and bitmasks, just step into gdb and do p /t and evaluate the the operations described above.

Resources