fork(4) download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4. import java.math.BigInteger;
  5.  
  6. class Ideone
  7. {
  8. private static BigInteger cubeRoot(BigInteger n)
  9. {
  10. // Using Newton's method, we approximate the cube root
  11. // of n by the sequence:
  12. // x_{i + 1} = \frac{1}{3} \left( \frac{n}{x_i^2} + 2 x_i \right).
  13. // See http://e...content-available-to-author-only...a.org/wiki/Cube_root#Numerical_methods.
  14.  
  15. // Initial estimate.
  16. BigInteger result = BigInteger.ZERO.setBit(n.bitLength() / 3);
  17.  
  18. BigInteger previousResult = BigInteger.ZERO;
  19.  
  20. final BigInteger three = BigInteger.valueOf(3);
  21. while (result.compareTo(previousResult) > 0) {
  22. previousResult = result;
  23. result = result.shiftLeft(1)
  24. .add(n.divide(previousResult.multiply(previousResult)))
  25. .divide(three);
  26. }
  27.  
  28. return result;
  29. }
  30.  
  31. public static void main (String[] args) throws java.lang.Exception
  32. {
  33. final int upperLimit = 5 * 5 * 5;
  34. for (int i = 0; i <= upperLimit; i++) {
  35. System.out.printf("%d %s%n", i, cubeRoot(BigInteger.valueOf(i)));
  36. }
  37. }
  38. }
Success #stdin #stdout 0.11s 381248KB
stdin
Standard input is empty
stdout
0 0
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 2
9 2
10 2
11 2
12 2
13 2
14 2
15 2
16 2
17 2
18 2
19 2
20 2
21 2
22 2
23 2
24 2
25 2
26 2
27 3
28 3
29 3
30 3
31 3
32 3
33 3
34 3
35 3
36 3
37 3
38 3
39 3
40 3
41 3
42 3
43 3
44 3
45 3
46 3
47 3
48 3
49 3
50 3
51 3
52 3
53 3
54 3
55 3
56 3
57 3
58 3
59 3
60 3
61 3
62 3
63 3
64 4
65 4
66 4
67 4
68 4
69 4
70 4
71 4
72 4
73 4
74 4
75 4
76 4
77 4
78 4
79 4
80 4
81 4
82 4
83 4
84 4
85 4
86 4
87 4
88 4
89 4
90 4
91 4
92 4
93 4
94 4
95 4
96 4
97 4
98 4
99 4
100 4
101 4
102 4
103 4
104 4
105 4
106 4
107 4
108 4
109 4
110 4
111 4
112 4
113 4
114 4
115 4
116 4
117 4
118 4
119 4
120 4
121 4
122 4
123 4
124 4
125 5