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. for (int i = 0; i < expo; i++) {
  9. result *= base;
  10.  
  11. if (result > limit)
  12. return result;
  13. }
  14. return result;
  15. }
  16.  
  17. // function to find the
  18. // n-th root of m
  19. static int nthRoot(int n, int m) {
  20. // n-th root of 0 is 0
  21. if (m == 0) return 0;
  22.  
  23. // If n is 1, the answer
  24. // is m itself
  25. if (n == 1) return m;
  26.  
  27. // binary search to find
  28. // the integer root
  29. int low = 1, high = m;
  30. while (low <= high) {
  31. int mid = (low + high) / 2;
  32.  
  33. // compute mid^n and compare it with m
  34. int val = power(mid, n, m);
  35.  
  36. if (val == m)
  37. return mid;
  38. else if (val < m)
  39. low = mid + 1;
  40. else
  41. high = mid - 1;
  42. }
  43.  
  44. return -1;
  45. }
  46.  
  47. public static void main(String[] args) {
  48. int n = 3, m = 27;
  49.  
  50. int result = nthRoot(n, m);
  51. System.out.println(result);
  52. }
  53. }
Success #stdin #stdout 0.09s 54604KB
stdin
Standard input is empty
stdout
3