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. public static double EPSILON = 0.001;
  11.  
  12. public static double power(double y, int n) {
  13. double r = y;
  14. for(int i = n; i > 1; i--) {
  15. r = r * y;
  16. }
  17. return r;
  18. }
  19.  
  20. public static double f(double y, double x, int n) {
  21. return power(y, n) - x;
  22. }
  23.  
  24. public static double fDiff(double y, int n) {
  25. return n*power(y, n-1);
  26. }
  27.  
  28. public static double iter(double yAlt, double x, int n) {
  29. return yAlt - f(yAlt, x, n) / fDiff(yAlt, n);
  30. }
  31.  
  32. public static double rootNofX(double x, int n) {
  33. double yAlt = 1;
  34. double yNew;
  35. while(true) {
  36. yNew = iter(yAlt, x, n);
  37. if(Math.abs(yNew - yAlt) < EPSILON) {
  38. return yNew;
  39. }
  40. yAlt = yNew;
  41. }
  42. }
  43.  
  44. public static void main (String[] args) throws java.lang.Exception
  45. {
  46. System.out.println(rootNofX(2,2));
  47. }
  48. }
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
1.4142135623746899