Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid automatic conversion from Fixnum to Bignum in Ruby

I am porting an algorithm from C# to Ruby. This algorithm has one method that returns an int that overflows sometimes.

    private static int NextRandom(int n)
    {
        return 1234567890 * n + 12345;
    }

The algorithm takes advantage of the overflow to avoid that the values returned by this function get out of range. However, Ruby behaves differently and it automatically converts the values to Bignum which does not seem to have a limit... How can I achieve the same in Ruby?

like image 233
miguelSantirso Avatar asked May 17 '26 23:05

miguelSantirso


1 Answers

If you want a number to wrap at a certain level, you may need to manually limit it:

def next_random(n)
  (1234567890 * n + 12345) % 0x7FFFFFFF
end

You can pick whatever limit you want, where that example is 32-bit signed.

I don't think you're able to lock numerical calculations to an arbitrary range.

like image 118
tadman Avatar answered May 19 '26 14:05

tadman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!