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. public static void main(String[] args) {
  10. //In this first call, no terms are used since none are greater
  11. //than EPSILON which is 2.
  12. System.out.printf("%.10f\n", addInverses(2)) ;
  13. System.out.println("0.0000000000 is expected.") ;
  14. System.out.println("------------") ;
  15.  
  16. //In this second call, no terms are used since none are greater
  17. //than EPSILON which is 1.
  18. System.out.printf("%.10f\n", addInverses(1)) ;
  19. System.out.println("0.0000000000 is expected.") ;
  20. System.out.println("------------") ;
  21.  
  22. //In this third call, one term is used since only the first one (1)
  23. //is greater than EPSILON which is 0.5
  24. System.out.printf("%.10f\n", addInverses(0.5)) ;
  25. System.out.println("1.0000000000 is expected.") ;
  26. System.out.println("------------") ;
  27.  
  28. System.out.printf("%.10f\n", addInverses(0.3)) ;
  29. System.out.printf("%.10f is expected.\n", 1 + 0.5 + 1/3.0) ;
  30. System.out.println("------------") ;
  31.  
  32. System.out.printf("%.10f\n", addInverses(1E-4)) ;
  33. System.out.println("9.7875060360 is expected.") ;
  34. System.out.println("------------") ;
  35.  
  36. System.out.printf("%.10f\n", addInverses(1E-5)) ;
  37. System.out.println("------------") ;
  38. }
  39.  
  40. /**
  41.   Adds up 1 + 1/2 + 1/3 + ... + 1/n,
  42.   where 1/n is the last term in the sequence greater than a
  43.   given constant called EPSILON.
  44.   That is, we only use terms which are greater than EPSILON.
  45.  
  46.   For example, if EPSILON is 0.3, then return 1 + 1/2 + 1/3
  47.   and if EPSILON is 0.5, then return 1 (since 1/2 is not greater than 0.5)
  48.   @param EPSILON a small threshold, above which we keep adding 1/n,
  49.   for n = 1, 2, 3, ...
  50.   */
  51. //-----------Start below here. To do: approximate lines of code = 12
  52. // 1. write the static method
  53. public static double addInverses(double EPSILON) {
  54. double returnVal = 0,
  55. nextTerm = 0;
  56.  
  57. int counter = 1;
  58.  
  59. while ((nextTerm = (1.0 / counter++ )) > EPSILON)
  60. returnVal += nextTerm;
  61.  
  62. return returnVal;
  63. }
  64. //-----------------End here. Please do not remove this comment. Reminder: no changes outside the todo regions.
  65. }
Success #stdin #stdout 0.08s 380224KB
stdin
Standard input is empty
stdout
0.0000000000
0.0000000000 is expected.
------------
0.0000000000
0.0000000000 is expected.
------------
1.0000000000
1.0000000000 is expected.
------------
1.8333333333
1.8333333333 is expected.
------------
9.7875060360
9.7875060360 is expected.
------------
12.0901361299
------------