@Override public int nextSetBit(int i) { assert i <= size(); if (i < Long.SIZE) { long maskedWord = word0 & (WORD_MASK << i); if (maskedWord != 0) { return Long.numberOfTrailingZeros(maskedWord); } i = Long.SIZE; } i -= Long.SIZE; if (i < Long.SIZE) { long maskedWord = word1 & (WORD_MASK << i); if (maskedWord != 0) { return Long.numberOfTrailingZeros(maskedWord) + Long.SIZE; } i = Long.SIZE; } i -= Long.SIZE; if (i < Long.SIZE) { long maskedWord = word2 & (WORD_MASK << i); if (maskedWord != 0) { return Long.numberOfTrailingZeros(maskedWord) + 2 * Long.SIZE; } i = Long.SIZE; } i -= Long.SIZE; long maskedWord = word3 & (WORD_MASK << i); return maskedWord == 0 ? -1 : Long.numberOfTrailingZeros(maskedWord) + 3 * Long.SIZE; }
// Shifts long bits as double, if the digits is positive, left-shift; if // not, shift to right and calculate its carry. private static long shiftLongBits(long bits, long digits) { if (digits > 0) { return bits << digits; } // change it to positive long absdigits = -digits; if (!(Long.numberOfLeadingZeros(bits & ~DOUBLE_SIGN_MASK) <= (64 - absdigits))) { return 0; } long ret = bits >> absdigits; boolean halfbit = ((bits >> (absdigits - 1)) & 0x1) == 1; if (halfbit) { // some bits will remain after shifting, calculates its carry // subnormal if (Long.numberOfTrailingZeros(bits) < (absdigits - 1)) { ret = ret + 1; } if (Long.numberOfTrailingZeros(bits) == (absdigits - 1)) { if ((ret & 0x1) == 1) { ret = ret + 1; } } } return ret; }
@Override public int nextSetBit(int i) { assert i < length; final int i4096 = i >>> 12; final long index = indices[i4096]; final long[] bitArray = this.bits[i4096]; int i64 = i >>> 6; int o = Long.bitCount(index & ((1L << i64) - 1)); if ((index & (1L << i64)) != 0) { // There is at least one bit that is set in the current long, check if // one of them is after i final long bits = bitArray[o] >>> i; // shifts are mod 64 if (bits != 0) { return i + Long.numberOfTrailingZeros(bits); } o += 1; } final long indexBits = index >>> i64 >>> 1; if (indexBits == 0) { // no more bits are set in the current block of 4096 bits, go to the next one return firstDoc(i4096 + 1); } // there are still set bits i64 += 1 + Long.numberOfTrailingZeros(indexBits); final long bits = bitArray[o]; return (i64 << 6) | Long.numberOfTrailingZeros(bits); }
/** * Returns {@code n!}, that is, the product of the first {@code n} positive integers, or {@code 1} * if {@code n == 0}. * * <p><b>Warning:</b> the result takes <i>O(n log n)</i> space, so use cautiously. * * <p>This uses an efficient binary recursive algorithm to compute the factorial with balanced * multiplies. It also removes all the 2s from the intermediate products (shifting them back in at * the end). * * @throws IllegalArgumentException if {@code n < 0} */ public static BigInteger factorial(int n) { checkNonNegative("n", n); // If the factorial is small enough, just use LongMath to do it. if (n < LongMath.factorials.length) { return BigInteger.valueOf(LongMath.factorials[n]); } // Pre-allocate space for our list of intermediate BigIntegers. int approxSize = IntMath.divide(n * IntMath.log2(n, CEILING), Long.SIZE, CEILING); ArrayList<BigInteger> bignums = new ArrayList<BigInteger>(approxSize); // Start from the pre-computed maximum long factorial. int startingNumber = LongMath.factorials.length; long product = LongMath.factorials[startingNumber - 1]; // Strip off 2s from this value. int shift = Long.numberOfTrailingZeros(product); product >>= shift; // Use floor(log2(num)) + 1 to prevent overflow of multiplication. int productBits = LongMath.log2(product, FLOOR) + 1; int bits = LongMath.log2(startingNumber, FLOOR) + 1; // Check for the next power of two boundary, to save us a CLZ operation. int nextPowerOfTwo = 1 << (bits - 1); // Iteratively multiply the longs as big as they can go. for (long num = startingNumber; num <= n; num++) { // Check to see if the floor(log2(num)) + 1 has changed. if ((num & nextPowerOfTwo) != 0) { nextPowerOfTwo <<= 1; bits++; } // Get rid of the 2s in num. int tz = Long.numberOfTrailingZeros(num); long normalizedNum = num >> tz; shift += tz; // Adjust floor(log2(num)) + 1. int normalizedBits = bits - tz; // If it won't fit in a long, then we store off the intermediate product. if (normalizedBits + productBits >= Long.SIZE) { bignums.add(BigInteger.valueOf(product)); product = 1; productBits = 0; } product *= normalizedNum; productBits = LongMath.log2(product, FLOOR) + 1; } // Check for leftovers. if (product > 1) { bignums.add(BigInteger.valueOf(product)); } // Efficiently multiply all the intermediate products together. return listProduct(bignums).shiftLeft(shift); }
/** Return the first document that occurs on or after the provided block index. */ private int firstDoc(int i4096) { long index = 0; while (i4096 < indices.length) { index = indices[i4096]; if (index != 0) { final int i64 = Long.numberOfTrailingZeros(index); return (i4096 << 12) | (i64 << 6) | Long.numberOfTrailingZeros(bits[i4096][0]); } i4096 += 1; } return DocIdSetIterator.NO_MORE_DOCS; }
/** * Find the index of the next set bit greater or equal to i, returns -1 if none found. * * @param i starting index * @return index of the next set bit */ public int nextSetBit(final int i) { int x = i >> 6; // i / 64 with sign extension long w = bitmap[x]; w >>>= i; if (w != 0) { return i + Long.numberOfTrailingZeros(w); } for (++x; x < bitmap.length; ++x) { if (bitmap[x] != 0) { return x * 64 + Long.numberOfTrailingZeros(bitmap[x]); } } return -1; }
/** * Find the index of the next unset bit greater or equal to i, returns -1 if none found. * * @param i starting index * @return index of the next unset bit */ public short nextUnsetBit(final int i) { int x = i / 64; long w = ~bitmap[x]; w >>>= i; if (w != 0) { return (short) (i + Long.numberOfTrailingZeros(w)); } ++x; for (; x < bitmap.length; ++x) { if (bitmap[x] != ~0L) { return (short) (x * 64 + Long.numberOfTrailingZeros(~bitmap[x])); } } return -1; }
@Override public long nextClearBit(long fromIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException(); long fromLongIndex = fromIndex >> 6; if (fromLongIndex >= longLength) return NOT_FOUND; long l = (~bytes.readLong(fromLongIndex << 3)) >>> fromIndex; if (l != 0) { return fromIndex + Long.numberOfTrailingZeros(l); } for (long i = fromLongIndex + 1; i < longLength; i++) { l = ~bytes.readLong(i << 3); if (l != 0) return (i << 6) + Long.numberOfTrailingZeros(l); } return NOT_FOUND; }
public static boolean isValidWildcard(Ip wildcard) { long w = wildcard.asLong(); long wp = w + 1l; int numTrailingZeros = Long.numberOfTrailingZeros(wp); long check = 1l << numTrailingZeros; return wp == check; }
public E next() { if (!hasNext()) throw new NoSuchElementException(); lastReturned = unseen & -unseen; lastReturnedIndex = unseenIndex; unseen -= lastReturned; return (E) universe[(lastReturnedIndex << 6) + Long.numberOfTrailingZeros(lastReturned)]; }
/** Writes a right-zero-extended value to {@code out}. */ public static void writeRightZeroExtendedValue(ByteOutput out, int type, long value) { // Figure out how many bits are needed to represent the value. int requiredBits = 64 - Long.numberOfTrailingZeros(value); if (requiredBits == 0) { requiredBits = 1; } // Round up the requiredBits to a number of bytes. int requiredBytes = (requiredBits + 0x07) >> 3; // Scootch the first bits to be written down to the low-order bits. value >>= 64 - (requiredBytes * 8); /* * Write the header byte, which includes the type and * requiredBytes - 1. */ out.writeByte(type | ((requiredBytes - 1) << 5)); // Write the value, per se. while (requiredBytes > 0) { out.writeByte((byte) value); value >>= 8; requiredBytes--; } }
private int addThread() { boolean set; int n; do { long l = bits.longValue(); long next = (l + 1) | l; n = Long.numberOfTrailingZeros(l + 1); set = bits.compareAndSet(l, next); } while (!set); return n; }
private void scoreMatches(LeafCollector collector, int base) throws IOException { long matching[] = this.matching; for (int idx = 0; idx < matching.length; idx++) { long bits = matching[idx]; while (bits != 0L) { int ntz = Long.numberOfTrailingZeros(bits); int doc = idx << 6 | ntz; scoreDocument(collector, base, doc); bits ^= 1L << ntz; } } }
/** * Returns the index of the first bit that is set to <code>true</code> that occurs on or after the * specified starting index. If no such bit exists then -1 is returned. * * <p>To iterate over the <code>true</code> bits in a <code>BitSet</code>, use the following loop: * * <p> * * <pre> * for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) { * // operate on index i here * }</pre> * * @param fromIndex the index to start checking from (inclusive). * @return the index of the next set bit. * @throws IndexOutOfBoundsException if the specified index is negative. */ public int nextSetBit(int fromIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex: " + fromIndex); if (fromIndex >= size) return -1; int u = wordIndex(fromIndex); long word = words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); if (++u == words.length) return -1; word = words[u]; } }
public E next() { if (mask == 0) { throw new NoSuchElementException(); } int ordinal = Long.numberOfTrailingZeros(mask) + index * BIT_IN_LONG; last = enums[ordinal]; currentBits &= ~mask; computeNextElement(); return last; }
/** @return true if the estimation was affected by this addition */ public boolean add(long value) { BucketAndHash bucketAndHash = fromHash(computeHash(value), estimator.getNumberOfBuckets()); int lowestBitPosition = Long.numberOfTrailingZeros(bucketAndHash.getHash()) + 1; if (estimator.getClass() == SparseEstimator.class && (estimator.estimateSizeInBytes() >= DenseEstimator.estimateSizeInBytes(estimator.getNumberOfBuckets()) || lowestBitPosition >= SparseEstimator.MAX_BUCKET_VALUE)) { estimator = new DenseEstimator(estimator.buckets()); } return estimator.setIfGreater(bucketAndHash.getBucket(), lowestBitPosition); }
public static String print(long bitmap) { StringBuilder sb = new StringBuilder(ZEROS); while (bitmap != 0) { long bit = Long.lowestOneBit(bitmap); int pos = Long.numberOfTrailingZeros(bit); sb.replace(63 - pos, 64 - pos, "1"); bitmap &= ~bit; } for (int x = 0; x < 7; x++) { sb.insert(8 + (9 * x), "_"); } sb.insert(0, "0b").append("L"); return sb.toString(); }
private static IntArray toIndexArray(long[] supportA, long[] supportB, IntArray indices) { if (indices == null) { indices = new IntArray(); } else { indices.clear(); } for (int i = 0; i < supportA.length; i++) { long commonSupport = supportA[i] & supportB[i]; while (commonSupport != 0) { final int index = Long.numberOfTrailingZeros(commonSupport); indices.add(index + i * 64); commonSupport ^= (1L << index); } } return indices; }
/** * Returns the index of the first bit that is set to <code>false</code> that occurs on or after * the specified starting index. * * @param fromIndex the index to start checking from (inclusive). * @return the index of the next clear bit. * @throws IndexOutOfBoundsException if the specified index is negative. */ public int nextClearBit(int fromIndex) { // Neither spec nor implementation handle bitsets of maximal length. // See 4816253. if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex: " + fromIndex); if (fromIndex >= size) return -1; int u = wordIndex(fromIndex); if (u >= words.length) return fromIndex; long word = ~words[u] & (WORD_MASK << fromIndex); while (true) { if (word != 0) return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); if (++u == words.length) return -1; word = ~words[u]; } }
private static int nextSetBit(int bitIndex, int[] bits, int bitsLength) { int wordIndex = bitIndex >> INT_BITS_SHIFT; if (wordIndex >= bitsLength) { return -1; } int word = bits[wordIndex] & (-1 << bitIndex); while (true) { if (word != 0) { return (wordIndex << INT_BITS_SHIFT) + Long.numberOfTrailingZeros(word); } if (++wordIndex == bitsLength) { return -1; } word = bits[wordIndex]; } }
public long get(int index) { long highBit = skipIndex[(index >>> 7) * 2]; long previousValue = skipIndex[((index >>> 7) * 2) + 1]; long highBitValue = previousValue >> numLowBits; int currentHighBitLongIndex = (int) (highBit >>> 6); int currentHighBitBitIndex = (int) (highBit & 0x3F); int numBitsToRead = index & 0x7F; long curVal = highBits.get(currentHighBitLongIndex); curVal >>>= currentHighBitBitIndex; int bitCount = Long.bitCount(curVal); while (numBitsToRead >= bitCount) { highBitValue += 64 - currentHighBitBitIndex - bitCount; numBitsToRead -= bitCount; currentHighBitBitIndex = 0; currentHighBitLongIndex++; curVal = highBits.get(currentHighBitLongIndex); bitCount = Long.bitCount(curVal); } int encodedHighBitValue = 0; for (int i = 0; i <= numBitsToRead; i++) { encodedHighBitValue = Long.numberOfTrailingZeros(curVal); highBitValue += encodedHighBitValue; curVal >>>= encodedHighBitValue + 1; } long lowBitData = getLowBits(index); if (lowBitData == 0 && encodedHighBitValue == 0 && (numBitsToRead != 0 || currentHighBitBitIndex != 0 || (currentHighBitLongIndex == 0 || highBits.get(currentHighBitLongIndex - 1) < 0))) { return -1; } return (highBitValue << numLowBits) | lowBitData; }
public void add(long value) { BucketAndHash bucketAndHash = BucketAndHash.fromHash(computeHash(value), buckets.length); int bucket = bucketAndHash.getBucket(); int lowestBitPosition = Long.numberOfTrailingZeros(bucketAndHash.getHash()) + 1; int previous = buckets[bucket]; if (previous == 0) { nonZeroBuckets++; } if (lowestBitPosition > previous) { currentSum -= 1.0 / (1L << previous); currentSum += 1.0 / (1L << lowestBitPosition); buckets[bucket] = (byte) lowestBitPosition; } }
/** * Constructs a HilbertCurve with the specified dimension count and side length * * @param dimension the number of dimensions to use, all with equal length; must be between 2 and * 31 * @param sideLength the length of a side, which will be rounded up to the next-higher power of * two if it isn't already a power of two. sideLength ^ dimension must be less than 2^31. */ public HilbertCurve(int dimension, int sideLength) { if (dimension > 31) dimension = 31; dims = dimension; if (sideLength <= 1) { sideLength = 2; } side = HilbertUtility.nextPowerOfTwo(sideLength); bits = Long.numberOfTrailingZeros(side); if (bits * dims >= 31) { bits = 31 / dims; side = 1 << bits; } dimensionality = new int[dims]; offsets = new int[dims]; Arrays.fill(dimensionality, side); maxDistance = 1 << (bits * dims); }
@Override public BoardSquare next() { prev = unseen & -unseen; unseen -= prev; return BoardSquare.values()[Long.numberOfTrailingZeros(prev)]; }
/** * @return 1-indexed alloc index, to allow {@code slot != 0} conditions, i. e. allocIndex = 0 * means empty hash table slot */ final long alloc() { long bitSet = this.bitSet; this.bitSet = (bitSet - 1) & bitSet; return Long.numberOfTrailingZeros(bitSet) + 1; }