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 void main (String[] args) throws java.lang.Exception
  11. {
  12. System.out.println("Rec: " + RecursiveFunction(1000));
  13. System.out.println("Flat0: " + NonRecursiveFunction0(1000));
  14. System.out.println("Flat1: " + NonRecursiveFunction1(1000));
  15. }
  16.  
  17. static float RecursiveFunction(int num){
  18. //The num parameter represents the denominator that will be used
  19. //The recursive function is continually called at lower increments of num
  20.  
  21. //If num is one, return 1 and do not call RecursiveFunction again
  22. if (num == 1) {
  23. return 1;
  24. }
  25. //Otherwise, return 1/num (in floating point decimal) and call RecursiveFunction with a parameter of num - 1
  26. else {
  27. return 1/(float)num + RecursiveFunction(num - 1);
  28. }
  29. }
  30.  
  31. //A Non-recursive version of RecursiveFunction that will be used to test RecursiveFunction
  32. static float NonRecursiveFunction0(int num) {
  33. //The total variable adds up the fractions
  34. float total = 0;
  35. //While num is greater than zero, add 1/num to total and then subtract 1 from num
  36. while (num > 0) {
  37. total += 1/(float)num;
  38. num -= 1;
  39. }
  40. return total;
  41. }
  42.  
  43. //A Non-recursive version of RecursiveFunction that will be used to test RecursiveFunction
  44. static float NonRecursiveFunction1(int num) {
  45. //The total variable adds up the fractions
  46. float total = 0;
  47. //While num is greater than zero, add 1/num to total and then subtract 1 from num
  48. for (int i = 1; i <= num; ++i)
  49. {
  50. total += 1.0f / i;
  51. }
  52. return total;
  53. }
  54. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
Rec:   7.4854784
Flat0: 7.4854717
Flat1: 7.4854784