#!/usr/bin/env ruby M = 2147483647 def calc(arr, m) v = M index = 0 out = arr.dup while (v > 0) do v += arr[index] #puts "index #{index} - v is #{v}, m is #{m[index]}" out[index] = v % (m[index] + 1) v /= (m[index] + 1) index += 1 end out end p calc([540, 800, 1200, 710], [M - 10, M - 11, M - 12, M - 13]) p calc([M - 1, 800, 1200, 710], [M - 1, 800, M - 1, M - 1])