Performs modulo division using Knuth's floored division algorithm. - Android java.lang

Android examples for java.lang:Math

Description

Performs modulo division using Knuth's floored division algorithm.

Demo Code

/*// ww w  .j av a  2s. c  om
 * Copyright (C) 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
//package com.java2s;

public class Main {
    /**
     * Performs modulo division using Knuth's floored division algorithm.
     * Returns a result with the same sign as the divisor.
     * <p>
     * This is distinct from Java's modulo (%) operator, which uses truncated
     * division and returns a result with the same sign as the dividend.
     *
     * @param dividend The number to divide.
     * @param divisor The number by which to divide.
     * @return The remainder of division of the {@code dividend} by the
     *         {@code divisor} with the same sign as the {@code divisor}.
     */
    public static int flooredModulo(int dividend, int divisor) {
        return (dividend - (divisor * (dividend / divisor)));
    }
}

Related Tutorials