1

I built the following function that finds the nth root of a number in Python:

def find_root(base, nth_root, top = None, bottom = 0):
    if top == None: top = base

    half = (float(top) + float(bottom)) / 2.0 

    if half**nth_root == base or half == top or half == bottom:
        return half
    if half**nth_root > base:
        return find_root(base, nthRoot, half, bottom)
    if half**nth_root < base:
        return find_root(base, nthRoot, top, half)

As you can probably tell it is highly dependent upon default parameters. Is there (1) a better way to do this (I want it to be recursive), and (2) (this question probably has the same answer as 1) how can I do this in Java if the language does not support default parameters?

I'm new to Java and trying to work out the differences.

Thanks,

Michael G.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
mjgpy3
  • 8,597
  • 5
  • 30
  • 51

2 Answers2

4

You can use method overloading to simulate default parameters:

int find_root(int base, int nth_root) {
  return find_root(base, nth_root, -1, 0);
}

int find_root(int base, nth_root, int top, int bottom) {
    // ...
}
João Silva
  • 89,303
  • 29
  • 152
  • 158
0

You can also use varargs feature. Example here.

Odysseus
  • 1,032
  • 2
  • 12
  • 14