How to check if number is divisible in c#?

浪尽此生 提交于 2020-01-13 18:23:30

问题


I need to know how to do this procedure.

calculation1: 1/4 = 0,25
calculation2: 1/8 = 0,125
calculation3: 47/183 = 0,25683060109289617486338797814207......
calculation4: 58/889 = 0,06524184476940382452193475815523......
calculation5: 1/5 = 0,2

The results of calculations 1, 2 and 5 will give a short result, no periods or and endless string of digits. The results of calculations 3 and 4 are very long and complicated.

How can I check which calculation is an "easy one" and gives a "short" result.

I tried this and it gave a wrong result for sure... like you can see, the results of the calculations have the datatype double in my application.

static bool IsInt(double x)
    {
        try
        {
            int y = Int32.Parse(x.ToString());
            return true;
        }
        catch
        {
             return false;
        }
    }

I hope it is clear what I'm asking.


回答1:


If after reducing the fraction as much as possible, the denominator can be expressed as a power of 2 multiplied by a power of 5, then the decimal representation terminates. Otherwise it repeats indefinitely.

You could test if your division is "good" as follows:

public bool IsGoodDivision(int a, int b)
{
    while (b % 2 == 0) { b /= 2; }
    while (b % 5 == 0) { b /= 5; }
    return a % b == 0;
}

See it working online: ideone

Note that I am passing the numerator and denominator separately to the method. If you do the division first, then pass the result to your method, you lose precision due to floating point representation error.

Also for production code you should check that b != 0 because it is not allowed to divide by 0. Without the check the above code would go into an infinite loop.




回答2:


I guess it depends on your definition of "good result" or "easy one". But I think what you want is the Modulus Operator.



来源:https://stackoverflow.com/questions/12097805/how-to-check-if-number-is-divisible-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!