Home > database >  Confused by result of modulo in Solidity
Confused by result of modulo in Solidity

Time:05-03

Just going through some learning pains and wanted to know if anyone could help.

My current goal on the course I'm on is to return a bool value from a function depending on if the 2nd uint divides evenly into the first uint.

I have the correct false logic in place according to the site but it still fails on the true logic.

This is the current function I have created

function dividesEvenly(uint x, uint y) public pure returns(bool) {
    if (y % x == 0) {
        return true;
    } else if (y % x != 0) {
        return false;
    }
 }

One of the test cases is (4,2) which I input into it myself mainly and it does chuck out a false. However doing 4 % 2 provides 0 which should return true so I'm not entirely sure what I've done wrong here.

Any help appreciated.

CodePudding user response:

The modulo operation in your snippet is reversed - y % x. So instead of 4 % 2 (result 0), it calculates 2 % 4 (result 2).

Solution: Reverse back the arithmetics

// the reminder after dividing 4 by 2 is 0
// 4 % 2 == 0

if (x % y == 0) {
    return true;
}
  • Related