let n = 8

let bit = Array.make (n + 1) 0

let lowbit i =
  let r = ref 1 in
  while !r * 2 <= i && i mod (!r * 2) = 0 do
    r := !r * 2
  done;
  !r

let rec update i delta =
  if i <= n then begin
    bit.(i) <- bit.(i) + delta;
    update (i + lowbit i) delta
  end

let rec prefix_sum i =
  if i <= 0 then 0
  else bit.(i) + prefix_sum (i - lowbit i)

let range_sum l r = prefix_sum r - prefix_sum (l - 1)

;;

let a = [| 1; 3; 5; 7; 9; 11; 13; 15 |] in
for i = 0 to n - 1 do
  update (i + 1) a.(i)
done;
let total = prefix_sum n in
update 1 100;
let after = prefix_sum n in
total + after
