Assuming X = A + B * C, where A & B are integers, C is irrational; Find A & B given X & C

46 Views Asked by At

I'm looking for an efficient algorithm which can solve this problem. Can I do better than with the following brute force algoritm in C++?

 pair<float, float> factorize(float value) {
        float min_err = 1.0f;
        float best_a = 0.0f, best_b = 0.0f;
        const float c = sqrt(3);

        for(int b = 0, max = value / c; b <= max; b++) {
            float t = value - c * b;

            float err = abs(t - round(t));
            if(err < min_err) {
                min_err = err;
                best_b = b;
                best_a = t;
            }
        }

        return {best_a, best_b};
    }

It simply looks through every possible combination of A & B and tries to find the best one.