3
\$\begingroup\$
  • Input: Real number y and Integer number x
  • Output: x^y
  • Constraint: Must be done in O(log(y)) time.

Notice that O(log(y)) is O(length-of(y)).

public static double expon(double x, int y){
    double result = 1.0;

    double part = x;
    for (int i = 0; i < 32; i++){
        if (((y >> i) & 1) == 1){
            result *= part;
        }
        part *= part;
    }   

    return result;
}
\$\endgroup\$

3 Answers 3

1
\$\begingroup\$

Your code is lacking comments that explain the why, ideally every non-trivial math programme should include a brief description of the algoritmh used.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ I think it is better for the code to be self documenting. It's the only way to ensure that comments don't get obsolete when the code gets changed. Said that, I would definitely add some details in the method Javadoc. It should contain information about what the parameters are expected to be, their accepted values, the produced results and indications on the algorithm used when, as in this case, they are relevant \$\endgroup\$ Commented Feb 1, 2015 at 22:32
  • \$\begingroup\$ Eccellente point @mario in my opinion too the best kind of comments is ----doc. (In this case javadoc.) \$\endgroup\$
    – Caridorc
    Commented Feb 2, 2015 at 12:56
1
\$\begingroup\$

I'd try to make your code more readable by giving a meaningful name to the variables you use. What about changing the signature of your method to

public static double exponentiate(double base, int exponent)

I think it is worth it, even if you're implementing a simple mathematical function like this one.

I'd also try to make it clear what you're doing with the ((y >> i) & 1) == 1 expression. What about introducing an isBitSet variable? I think introducing it (or an equivalent bool isByteSet(int number, int position) function) would make your code more readable. I'd also rename part to something like candidateFactor, which would make it clear that you're computing the factor corresponding to each binary digit and deciding whether to use it or not according to isBitSet.

I'd also recommend you to do some validation of your input values. What happens if you get passed a negative value for exponent? You can either make it an exceptional case and throw an IllegalArgumentException or handle it knowing that x^y = 1/(x^(-y))

\$\endgroup\$
0
\$\begingroup\$

Your style seems to be consistent. The code is acceptably clear.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.