forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModulo.java
40 lines (36 loc) · 894 Bytes
/
Modulo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.rampatra.bits;
/**
* Created by IntelliJ IDEA.
*
* @author: ramswaroop
* @date: 6/8/15
* @time: 11:28 PM
*/
public class Modulo {
/**
* Returns {@param n} modulo {@param d} provided
* {@param d} is a power of 2.
*
* @param n
* @param d
* @return
*/
public static int getNmoduloD(int n, int d) {
return n & (d - 1);
}
public static void main(String a[]) {
System.out.println(getNmoduloD(18, 8));
System.out.println(getNmoduloD(18, 4));
System.out.println(getNmoduloD(13, 4));
System.out.println(getNmoduloD(13, 1));
System.out.println(getNmoduloD(2, 2));
System.out.println(getNmoduloD(13, 16));
}
}
/**
* Consider example, for 18 % 8
* <p>
* 18 = 10010
* 7 = 00111 (8 = 2 ^ 3, therefore mask has to have three 1's)
* 2 = 00010 (remainder = 18 & (8-1))
*/