How to check if number is divisible in c#?

16,504

Solution 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.

Solution 2

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

Share:
16,504
Abi
Author by

Abi

Updated on June 04, 2022

Comments

  • Abi
    Abi almost 2 years

    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.