#!/usr/bin/env ruby M = 2147483647 def calc(v, arr, 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(M, [540, 800, 1200, 710], [M - 10, M - 11, M - 12, M - 13]) p calc(M, [M - 1, 800, 1200, 710], [M - 1, 800, M - 1, M - 1]) p calc(1650000, [0, 0, 0, 0], [5300, 2499, 12631, 171244])