Advertisement
Guest User

Untitled

a guest
Nov 17th, 2017
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. import java.util.Scanner;
  2. /**
  3. This program calculates the geometric and
  4. harmonic progression for a number entered
  5. by the user.
  6. */
  7. public class Progression {
  8. public static void main(String[] args) {
  9. Scanner keyboard = new Scanner (System.in);
  10. System.out.println("This program will calculate " +
  11. "the geometric and harmonic " +
  12. "progression for the number " +
  13. "you enter.");
  14. System.out.print("Enter an integer that is " +
  15. "greater than or equal to 1: ");
  16. int input = keyboard.nextInt();
  17. // Match the method calls with the methods you write
  18. int geomAnswer = geometricRecursive(input);
  19. double harmAnswer = harmonicRecursive(input);
  20. System.out.println("Using recursion:");
  21. System.out.println("The geometric progression of " +
  22. input + " is " + geomAnswer);
  23. System.out.println("The harmonic progression of " +
  24. input + " is " + harmAnswer);
  25. // Match the method calls with the methods you write
  26. geomAnswer = geometricIterative(input);
  27. harmAnswer = harmonicIterative(input);
  28. System.out.println("Using iteration:");
  29. System.out.println("The geometric progression of " +
  30. input + " is " + geomAnswer);
  31. System.out.println("The harmonic progression of " +
  32. input + " is " + harmAnswer);
  33. }
  34. // ADD LINES FOR TASK #2 HERE
  35.  
  36. public static int geometricRecursive(int x){
  37. if(x == 1)
  38. return 1;
  39. else {
  40. return x * geometricRecursive(x - 1);
  41. }
  42. }
  43.  
  44. public static double harmonicRecursive(double x){
  45. if(x <= 1.0) {
  46. return 1.0;
  47. }
  48. else {
  49. return x * harmonicRecursive(1.0 /(x - 1.0 ));
  50. }
  51. }
  52.  
  53. public static int geometricIterative(int num){
  54. int result = 0;
  55. if(result == 1)
  56. return result;
  57. else
  58. for(int i = 2; i < num; i++){
  59. result = (i * (i + 1));
  60. }
  61. return result;
  62. }
  63.  
  64. public static int harmonicIterative(int num){
  65. int result = 0;
  66. if (result == 1)
  67. return result;
  68. else
  69. for (int i = 2; i < num; i ++){
  70. result = (i * (1/(i+1)));
  71. }
  72. return result;
  73. }
  74.  
  75.  
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement