fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. private static int check(long mid, int n, long m) {
  11. long ans = 1;
  12. for (int i = 1; i <= n; i++) {
  13. if (mid > m / ans) {
  14. return 2;
  15. }
  16. ans *= mid;
  17. }
  18.  
  19. if (ans == m) {
  20. return 1;
  21. }
  22. return 0;
  23. }
  24.  
  25. public static long NthRoot(int n, long m) {
  26. if (m == 0 || m == 1) {
  27. return m;
  28. }
  29. if (n == 1) {
  30. return m;
  31. }
  32.  
  33. long low = 1;
  34. long high = m;
  35.  
  36. while (low <= high) {
  37. long mid = low + (high - low) / 2;
  38. int val = check(mid, n, m);
  39.  
  40. if (val == 1) {
  41. return mid;
  42. } else if (val == 0) {
  43. low = mid + 1;
  44. } else {
  45. high = mid - 1;
  46. }
  47. }
  48.  
  49. return -1;
  50. }
  51.  
  52. public static void main(String[] args) {
  53. int n1 = 3;
  54. long m1 = 27;
  55. System.out.println(n1 + "th root of " + m1 + " is: " + NthRoot(n1, m1));
  56.  
  57. }
  58. }
Success #stdin #stdout 0.17s 57988KB
stdin
Standard input is empty
stdout
3th root of 27 is: 3