optimization to use divmod instead of discrete div and mod operations (from kseistrup on GitHub)