Frager
Frager

Reputation: 1

Simple recursive to iterative

I think my solution is too complicated, how can I simplify it?

Problem:

public static int calc (int g, int h) {
    if (h > 5) {
        g += h;
        return calc (g, h − 2) ∗ 2;
    } else {
        return g;
    }
}

My solution:

public static int calc (int g, int h) {
    int counter = 0;
    for (; h > 5; h -= 2){
        g += h;
        counter++;
    }
    return g * (int) Math.pow(2, counter);
}  

Upvotes: 0

Views: 33

Answers (1)

cdlane
cdlane

Reputation: 41872

I'd be more inclined to simplify your original recursive code:

public static int calc(int g, int h) {
    if (h <= 5) {
        return g;
    }

    return 2 * calc(g + h, h - 2);
}

But if I were to simplify your iterative code, I'd try to avoid introducing the floating point Math.pow() and keep the whole operation int:

public static int calc(int g, int h) {
    int power;

    for (power = 1; h > 5; h -= 2) {
        g += h;
        power *= 2;
    }

    return g * power;
}

Upvotes: 1

Related Questions