Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- /**
- This program calculates the geometric and
- harmonic progression for a number entered
- by the user.
- */
- public class Progression {
- public static void main(String[] args) {
- Scanner keyboard = new Scanner (System.in);
- System.out.println("This program will calculate " +
- "the geometric and harmonic " +
- "progression for the number " +
- "you enter.");
- System.out.print("Enter an integer that is " +
- "greater than or equal to 1: ");
- int input = keyboard.nextInt();
- // Match the method calls with the methods you write
- int geomAnswer = geometricRecursive(input);
- double harmAnswer = harmonicRecursive(input);
- System.out.println("Using recursion:");
- System.out.println("The geometric progression of " +
- input + " is " + geomAnswer);
- System.out.println("The harmonic progression of " +
- input + " is " + harmAnswer);
- // Match the method calls with the methods you write
- geomAnswer = geometricIterative(input);
- harmAnswer = harmonicIterative(input);
- System.out.println("Using iteration:");
- System.out.println("The geometric progression of " +
- input + " is " + geomAnswer);
- System.out.println("The harmonic progression of " +
- input + " is " + harmAnswer);
- }
- // ADD LINES FOR TASK #2 HERE
- public static int geometricRecursive(int x){
- if(x == 1)
- return 1;
- else {
- return x * geometricRecursive(x - 1);
- }
- }
- public static double harmonicRecursive(double x){
- if(x <= 1.0) {
- return 1.0;
- }
- else {
- return x * harmonicRecursive(1.0 /(x - 1.0 ));
- }
- }
- public static int geometricIterative(int num){
- int result = 0;
- if(result == 1)
- return result;
- else
- for(int i = 2; i < num; i++){
- result = (i * (i + 1));
- }
- return result;
- }
- public static int harmonicIterative(int num){
- int result = 0;
- if (result == 1)
- return result;
- else
- for (int i = 2; i < num; i ++){
- result = (i * (1/(i+1)));
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement