fork download
  1. class GfG {
  2.  
  3. // function to calculate base^expo
  4. // returns early if result exceeds the
  5. // given limit to avoid overflow
  6. static int power(int base, int expo, int limit) {
  7. int result = 1;
  8. // now multiply the number we chose by itself n times
  9. // stop early and return if it exceeds before reaching n times even
  10. for (int i = 0; i < expo; i++) {
  11. result *= base;
  12.  
  13. if (result > limit)
  14. return result;
  15. }
  16. return result;
  17. }
  18.  
  19. // function to find the
  20. // n-th root of m
  21. // to find nth room of m means to get the number which needs to be multiplied n times so that we get m
  22. static int nthRoot(int n, int m) {
  23. // n-th root of 0 is 0
  24. if (m == 0) return 0;
  25.  
  26. // If n is 1, the answer
  27. // is m itself
  28. if (n == 1) return m;
  29.  
  30. // binary search to find
  31. // the integer root
  32. int low = 1, high = m;
  33. while (low <= high) {
  34. int mid = (low + high) / 2;
  35.  
  36. // compute mid^n and compare it with m
  37. int val = power(mid, n, m);
  38. // choose a number in the middle of m, m/2 or whatever and
  39. // do x^n to it and see if it satisties .. can we have a number that gives m after multiplied it
  40. // by itself n times..
  41. if (val == m)
  42. return mid;
  43. else if (val < m)
  44. low = mid + 1;
  45. else
  46. high = mid - 1;
  47. }
  48.  
  49. return -1;
  50. }
  51.  
  52. public static void main(String[] args) {
  53. int n = 3, m = 64;
  54. // what can i multiply 3 times by itself to get 64.. 4 * 4 * 4
  55. int result = nthRoot(n, m);
  56. System.out.println(result);
  57. }
  58. }
Success #stdin #stdout 0.08s 54560KB
stdin
Standard input is empty
stdout
4