Here you can find the source of mods(long v, long m)
Parameter | Description |
---|---|
v | a value |
m | a modulus |
public static long mods(long v, long m)
//package com.java2s; //License from project: Open Source License public class Main { /**/* w w w . j a v a 2 s .co m*/ * 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; /** * Signed mod.<br> * The value returned lies in range [ -( |m| - 1 ) / 2 .. |m| / 2 ].<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 mods(int v, int m) { if (m <= 0) { if (m == 0) return NOT_FOUND; if (m == Integer.MIN_VALUE) { if (v < -1073741823 || v > 1073741824) v += m; return v; } m = -m; } v %= m; if (v > m >> 1) v -= m; else if (v < -((m - 1) >> 1)) v += m; return v; } /** * Signed mod.<br> * The value returned lies in range [ -( |m| - 1 ) / 2 .. |m| / 2 ].<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 mods(long v, long m) { if (m <= 0L) { if (m == 0L) return NOT_FOUND; if (m == Long.MIN_VALUE) { if (v < -4611686018427387903L || v > 4611686018427387904L) v += m; return v; } m = -m; } v %= m; if (v > m >> 1) v -= m; else if (v < -((m - 1L) >> 1)) v += m; return v; } }