Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add significant bits/fastLog2 operation for BigInts #67

Closed
dlesnoff opened this issue Jan 8, 2022 · 1 comment
Closed

Add significant bits/fastLog2 operation for BigInts #67

dlesnoff opened this issue Jan 8, 2022 · 1 comment

Comments

@dlesnoff
Copy link
Contributor

dlesnoff commented Jan 8, 2022

In order to improve modular exponentiation or to write other higher-order functions (functions that do not rely on BigInts internal representation), we might want to count the number of significant bits (bits after leading zeros, without the sign bit in complement representation of signed integers) or at least the logarithm in base 2 of the number.

We can determine the number of significant bits from the logarithm in base 2 as:
significantBits(n) = floor(log_2(n)) + 1

func significantBits*(n: BigInt): int =
  if n < 0:
    return significantBits(-n)
  fastLog2(n.limbs.high) + 32*(n.limbs.len-1)

How would you optimize the negative case ? Can we just take the two’s complement of the highest limb and then compute the fastLog2(n.limbs.high) ?

func significantBits*(n: BigInt): int =
  var highest_limb = n.limbs.high
  if n < 0:
    highest_limb = not n.limbs.high + 1
  fastLog2(highest_limb) + 32*(n.limbs.len-1)
@konsumlamm
Copy link
Contributor

I think you're misunderstanding how negative BigInts are stored. Negating a BigInt is just inverting the isNegative flag, nothing is stored in two's complement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants