Here you can find the source of mod(long v, long m)
Parameter | Description |
---|---|
v | a value |
m | a modulus |
public static long mod(long v, long m)
//package com.java2s; //License from project: Open Source License public class Main { /**//ww w .j av a 2 s.com * Some methods return this value as indication that the answer doesn't exist or is undefined.<br> * For example, when mod = 0 in modular arithmetics, or when a number isn't a perfect power and * a function should return its base. * <p>This constant equals to {@code Integer.MIN_VALUE} because {@code Integer.MIN_VALUE} * can't be a base of any perfect power that fits in long. Proof:<ul> * <li>Base of perfect square is a positive number.</li> * <li>Integer.MIN_VALUE<sup>3</sup> = ((-2)<sup>31</sup>)<sup>3</sup> = (-2)<sup>93</sup> < (-2)<sup>63</sup> = Long.MIN_VALUE.</li> * <li>Higher powers would give higher values.</li></ul> * So no power greater than one can return base = {@code Integer.MIN_VALUE} for any long integer. * <p>Also, any modular arithmetic operation returns non-negative value, * so negative values can be used as error codes. * <p>Error codes are more desirable than throwing an exception when performance matters. */ public static final int NOT_FOUND = Integer.MIN_VALUE; /** * Returns v (mod m).<br> * The value returned lies in range [ 0 .. |m| - 1 ].<br> * mod( x, m ) = mod( x, -m ).<br> * This method differs from v % m in that it always returns non-negative value.<br> * If m = 0 then {@link #NOT_FOUND} is returned. * @param v a value * @param m a modulus * @return v (mod m), or {@link #NOT_FOUND} if m = 0 */ public static int mod(int v, int m) { if (m == 0) return NOT_FOUND; v %= m; if (v < 0) { // Note: if m = Integer.MIN_VALUE then addition behaves exactly like subtraction. if (m < 0) v -= m; else v += m; } return v; } /** * Returns v (mod m).<br> * The value returned lies in range [ 0 .. |m| - 1 ].<br> * mod( x, m ) = mod( x, -m ).<br> * This method differs from v % m in that it always returns non-negative value.<br> * If m = 0 then {@link #NOT_FOUND} is returned. * @param v a value * @param m a modulus * @return v (mod m), or {@link #NOT_FOUND} if m = 0 */ public static long mod(long v, long m) { if (m == 0L) return NOT_FOUND; v %= m; if (v < 0L) { // Note: if m = Long.MIN_VALUE then addition behaves exactly like subtraction. if (m < 0L) v -= m; else v += m; } return v; } }