Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- /**
- * Write a description of class FactorialIterativeRecursive here.
- *
- * @author (Ruari Mears)
- * @version (1.1.3)
- */
- public class FactorialIterativeRecursive
- {
- /**
- * Uses nanoTime() to count execution time for each approach.
- */
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int input;
- int method;
- long begin;
- long end;
- long timeElapsed;
- System.out.println("Calculating factorial.");
- System.out.print("Enter a number: ");
- input = Integer.parseInt(scanner.nextLine());
- System.out.println("How do you want to calculate factorial of " + String.valueOf(input) + ":");
- System.out.println("1. Iteratively - using for");
- System.out.println("2. Iteratively - using while");
- System.out.println("3. Recursively.");
- System.out.print("Enter a number: ");
- method = Integer.parseInt(scanner.nextLine());
- switch (method) {
- case 1:
- begin = System.nanoTime();
- System.out.println("The result is: " + getFactorialIterationFor(input));
- end = System.nanoTime();
- timeElapsed = end - begin;
- System.out.println("The iterative (for) approach took "
- + String.valueOf(timeElapsed) + "ns");
- break;
- case 2:
- begin = System.nanoTime();
- System.out.println("The result is: " + getFactorialIterationWhile(input));
- end = System.nanoTime();
- timeElapsed = end - begin;
- System.out.println("The iterative (while) approach took "
- + String.valueOf(timeElapsed) + "ns");
- break;
- case 3:
- begin = System.nanoTime();
- System.out.println("The result is: " + getFactorialRecursion(input));
- end = System.nanoTime();
- timeElapsed = end - begin;
- System.out.println("The recursive approach took "
- + String.valueOf(timeElapsed) + "ns");
- break;
- }
- }
- /**
- * Implementation of iterative (for) factorial from:
- * https://stackabuse.com/calculate-factorial-with-java-iterative-and-recursive/
- */
- public static int getFactorialIterationFor(int n)
- {
- int result = 1;
- if (n > 1) {
- for (int i = 1; i <= n; i++) {
- result = result * i;
- }
- return result;
- } else {
- System.out.println("n has to be positive");
- return result;
- }
- }
- /**
- * Implementation of iterative (while) factorial from:
- * https://stackabuse.com/calculate-factorial-with-java-iterative-and-recursive/
- */
- public static int getFactorialIterationWhile(int n) {
- int result = 1;
- while (n > 1) {
- result = result * n;
- n -= 1;
- }
- return result;
- }
- /**
- * Implementation of recursive factorial from:
- * https://stackabuse.com/calculate-factorial-with-java-iterative-and-recursive/
- */
- public static int getFactorialRecursion(int n) {
- if (n <= 1) {
- return 1;
- } else {
- return n * getFactorialRecursion(n-1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement