Skip to content

Instantly share code, notes, and snippets.

@mlhoutel
Last active June 28, 2022 14:13
Show Gist options
  • Save mlhoutel/a54c210250826515839ca9eb6e8ba6ec to your computer and use it in GitHub Desktop.
Save mlhoutel/a54c210250826515839ca9eb6e8ba6ec to your computer and use it in GitHub Desktop.
public double GetValue(double x, int n) {
if (n == 0) { return 1; } // O(1)
return (n > 0) ? RecValue(x, n) : 1 / RecValue(x, -n); // O(n*log(n))
}
private double RecValue(double x, int n) {
if (n == 1) { return x; } // O(1)
int divider = 2; // O(1)
int remain = n % divider; // O(1)
int mult = remain == 0 ? n / divider : (n - 1) / divider; // O(1)
double val = GetValue(x, mult); // O(n*log(n))
for (int i = 0; i < divider - 1; i++) { val *= val; } // O(1)
for (int i = 0; i < remain; i++) { val *= x; } // O(1)
return val;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment