Home > Software engineering >  How to check whether number is divisible by another number WITHOUT conditional check (if, ternary, e
How to check whether number is divisible by another number WITHOUT conditional check (if, ternary, e

Time:10-30

I have a number, for example, X. I want to check if it is divisible by Y (another number). If it is divisible by Y, I need to return 1, otherwise 0. But I am not allowed to use if condition, ternary operator, equals, etc. Any suggestions?

CodePudding user response:

This expression returns true if the variable X is divisible by 3

X % 3 == 0

CodePudding user response:

You can use the modulo operator

return ((double)number) % 3.0d == 0

CodePudding user response:

if ((number % 3) == 0)
{
     Console.WriteLine(number);
}

CodePudding user response:

Without using any conditionals, including == (which is actually also a conditional underneath)

Bit-twiddling based on this answer

var mod = unchecked((uint)(a % b));
mod = ((mod - 1U) & ~mod) >> 31;
return Unsafe.As<uint, bool>(ref mod);

dotnetfiddle

  • Related