CIS 3020 Stupid

From In The Wings
Jump to navigation Jump to search

So, here is some really stupid code that I have come up with while I was taking this class.

Implementation of multiplication using recursion

  private static int mult(int a, int b) {
    int result;
    if (b<=1) {
      result = a;
    } else {
      result = a + mult(a,b-1);
    }
    return result;
  }

Implementation of Convergence Lecture

This was part of a lecture that showed us something about convergence. Apparently this particular convergence has never actually been proven by mathemeticians, but regardless this is an implementation of the convergence using recursion.

The actual convergence works like this:

  • Pick a positive integer
    • If that integer is even, divide it by two
    • If it is odd, multiply by three, then add one
  • Lather, rinse, repeat
  • Eventually this will converge on one, though it has never been proven mathematically

Here is the code:

import java.util.Scanner;

public class Converge {
  public static void main (String[] args) {
    System.out.println("Enter a positive integer:");
    Scanner sc = new Scanner(System.in);
    int num = sc.nextInt();
    converge(num);
  }

  private static int converge(int input) {
    System.out.printf("Input: %d\n", input);
    int output;
    if (input<=1) {
      output = input;
    } else {
      if (even(input)) {
        output = converge(input/2);
      } else {
        output = converge((mult(input, 3)) + 1);
      }
    }
    return output;
  }

  private static boolean even(int x) {
    return (x % 2 == 0);
  }

  private static int mult(int a, int b) {
    int result;
    if (b<=1) {
      result = a;
    } else {
      result = a + mult(a,b-1);
    }
    return result;
  }
}