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 Main
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. int a=2499;
  13. int b= 100;
  14. //System.out.println("Testing method triangleBelow with goal "+a+" and last "+b+"");
  15. int resInt=triangleBelow(a,b);
  16. //System.out.println("The result of triangleBelow is "+resInt+"");
  17. //System.out.println("Testing method sumReciprocals with n equals "+b+"");
  18. double resDbl= sumReciprocals(b);
  19. //System.out.println("The result of sumReciprocals is "+resDbl+"");
  20. int n= (int)(Math.random()*250+50);
  21. double myEstimate= estimatePi(n);
  22. System.out.println("After using up to "+n+" terms, the estimated value of pi is "+myEstimate+"");
  23. }
  24. public static int triangleBelow(int goal, int last)//Needs Tested, Worked
  25. {
  26. int sum = 0;
  27. for(int j=0;j<last; j++)
  28. {
  29. sum+=j;
  30. if(sum>=goal)
  31. {
  32. break;
  33. }
  34. }
  35. return sum;
  36. }
  37. public static double sumReciprocals(int n)//Needs tested, Worked
  38. {
  39. double sum= 0;
  40. for(int j=1; j<n+1; j++)
  41. {
  42. sum+=1.0/j;
  43. }
  44. return sum;
  45. }
  46. public static double estimatePi(int n) //Bonus
  47. {
  48. double sign= 1.0;
  49. double sum=0;
  50. for(int j=0;j<n; j++)
  51. {
  52. sum+= sign/(2*j+1);
  53. sign*=-1;
  54. if(sum*4>=3.14 && sum*4<=3.15)
  55. break;
  56. }
  57. return sum*4;
  58. }
  59. }
Success #stdin #stdout 0.11s 36576KB
stdin
Standard input is empty
stdout
After using up to 154 terms,  the estimated value of pi is 3.14999586659347