Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] Counting bits in a big_int
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2004-05-15 (11:14)
From: Markus Mottl <markus@o...>
Subject: Re: [Caml-list] Counting bits in a big_int
On Fri, 14 May 2004, Yaron Minsky wrote:
> Here's the fastest bitcounter I've been able to come up with.  It's
> about an order of magnitude faster than just counting bit by bit.

How about this:

open Big_int
open Nat

let nbits x =
  let nat = nat_of_big_int (abs_big_int x) in
  let nwords = num_digits_nat nat 0 (length_nat nat) in
  Sys.word_size * nwords - num_leading_zero_bits_in_digit nat (nwords - 1)

This runs another order of magnitude faster, and it's shorter, too :-)


Markus Mottl

To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: