Rounding Y To Make Mod(x,y) = 0

I have two variables, X and Y. X is some value that cannot be changed and Y is some random value less than 1 (most likely an irrational number as well) that cannot increase. I'm trying to figure out a way to round Y down, so as to make (X % Y = 0).

For example, if x = 2 and y = 0.0137, then x/y = 145.9854015~. Now to make x % y = 0, I have to round 0.0137 down to the nearest decimal that will do so, which would be Y = 0.0125.

I've come up with a few ways of doing this, but none of them work for all cases (for any x and y). Do you guys have any suggestions as to how I can tackle this?

Thanks in advance for any help!

- Ali
Last edited on
Divide X by an integer, starting with 1. If the result is lower than Y, set Y to the result. Otherwise, add 1 to X and try again.
So what you're saying is that I do this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double x = 2;
double xx;
double y = 0.0137;
int G = 0;
int S = 1;
while (G == 0)
{
    xx = x/S;
    if (xx < y)
    {
        y = xx;
        G = 1;
    }
    else
    {
        S = S + 1;
    }
}


But how does that make the modulus = 0? I think I may have misunderstood you.
If the algorithm works as I suspect, it will always result in a modulus of 0 (at least for reasonable, valid inputs).

A modulus of 0 really means that x is some multiple of Y. After the loop, y contains x / xx, so y = xx * x, making y a multiple of x. Moreover, this algorithm starts by dividing by 1, getting results in decreasing order until the result is less than y, so y will always be set to the valid result just below its previous value; it never rounds up.


In your case, x is 2 and y is 0.0137. The program will divide by 1, see that the result is 2 which is greater than 0.0137, and try again. Then it will divide by 2, see that the result is 1 which is greater than 0.0137, and try again. This will keep going until it reaches 146. 2.0 / 146 is just below 0.0137, and y will be reduced to that value. After that, x mod y should be as close as is reasonably possible to 0.
Last edited on
The issue is that the algorithm will usually generate irrational or rational but repeated numbers. For example, when running that algorithm for x = 2, y = 0.0137, it generates a y value of 0.013698630136986 (calculation done in MATLAB for this one example). Is there any way to do this so that it doesn't generate irrational or repeating numbers?
Topic archived. No new replies allowed.