fork(1) download
  1. import java.math.BigInteger;
  2.  
  3. class NthRoot {
  4. public static void main (String[] args) {
  5. example(7, "100001232101001010120320");
  6. }
  7. private static void example(int n, String xstr) {
  8. BigInteger x = new BigInteger(xstr);
  9. BigInteger y = root(n, x);
  10. BigInteger z = y.pow(n);
  11. BigInteger y1 = y.add(BigInteger.ONE);
  12. BigInteger z1 = y1.pow(n);
  13. System.out.println("floor(" + x + "^(1/" + n + ")) = " + y);
  14. System.out.println(y + "^" + n + " = " + z);
  15. System.out.println(y1 + "^" + n + " = " + z1);
  16. System.out.println();
  17. }
  18. private static BigInteger root(int n, BigInteger x) {
  19. for (int m = (x.bitLength() - 1)/n; m >= 0; --m) {
  20. BigInteger z = y.setBit(m);
  21. int cmp = z.pow(n).compareTo(x);
  22. if (cmp == 0) return z; // found exact root
  23. if (cmp < 0) y = z; // keep bit set
  24. }
  25. return y; // return floor of exact root
  26. }
  27. }
Success #stdin #stdout 0.11s 320512KB
stdin
Standard input is empty
stdout
floor(100001232101001010120320^(1/7)) = 1930
1930^7 = 99747303260050570000000
1931^7 = 100109643878654613881411