Jay
Jay

Reputation: 373

Can this be further optimised

public static bool IsDivisible(double p, double n, double r, double k)
    {
        double x = p;
        double a = 0.0, b = 0.0, c = 0.0;
        while (x <= n)
        {
            a += Math.Floor(n / x);
            if (x <= r)
                b += Math.Floor(r / x);
            if (x <= k)
                c += Math.Floor(k / x);
            x *= p;
        }
        return a > b + c ? true : false;
    }

This above code checks if a nCr is divisible by a number p.k is n-r. This function returns true if a particular nCr is divisible a number p.Can this be optimised further.

Upvotes: 1

Views: 113

Answers (1)

Mark Byers
Mark Byers

Reputation: 837916

Are your inputs are always positive integers? If so, then you can improve performance using int instead of double and using integer division instead of floating point division. Then you also won't need to call Math.Floor as integer division automatically truncates the result for you.

You can also simplify the last line to just this:

return a > b + c;

Upvotes: 4

Related Questions