Compute n modulo d without division(/) and modulo(%) operators, where d is a power of 2 number.

Let ith bit from right is set in d. For getting n modulus d, we just need to return 0 to i-1 (from right) bits of n as they are and other bits as 0.

For example if n = 6 (00..110) and d = 4(00..100). Last set bit in d is at position 3 (from right side). So we need to return last two bits of n as they are and other bits as 0, i.e., 00..010.

Now doing it is so easy, guess it….

Yes, you have guessing it right. See the below program.

[pastacode lang=”c” manual=”%23include%3Cstdio.h%3E%0A%20%0A%2F*%20This%20function%20will%20return%20n%20%25%20d.%0A%20%20%20d%20must%20be%20one%20of%3A%201%2C%202%2C%204%2C%208%2C%2016%2C%2032%2C%20%E2%80%A6%20*%2F%0Aunsigned%20int%20getModulo(unsigned%20int%20n%2C%20unsigned%20int%20d)%0A%7B%0A%20%20return%20(%20n%20%26%20(d-1)%20)%3B%0A%7D%20%20%20%20%20%20%20%20%20%0A%20%0A%2F*%20Driver%20program%20to%20test%20above%20function%20*%2F%0Aint%20main()%0A%7B%0A%20%20unsigned%20int%20n%20%3D%206%3B%0A%20%20unsigned%20int%20d%20%3D%204%3B%20%2F*d%20must%20be%20a%20power%20of%202*%2F%0A%20%20printf(%22%25u%20moduo%20%25u%20is%20%25u%22%2C%20n%2C%20d%2C%20getModulo(n%2C%20d))%3B%0A%20%0A%20%20getchar()%3B%0A%20%20return%200%3B%0A%7D%20″ message=”C Program” highlight=”” provider=”manual”/] [ad type=”banner”]