Skip to content

Instantly share code, notes, and snippets.

@frekele
Last active October 10, 2019 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frekele/d979cff9bf9f27759c86396dd7ec7375 to your computer and use it in GitHub Desktop.
Save frekele/d979cff9bf9f27759c86396dd7ec7375 to your computer and use it in GitHub Desktop.
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.Scanner;
public class IterativeFactor {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a factorial:");
long factor = in.nextLong();
System.out.println("#####################################################################");
System.out.println("FACTORIAL: !" + factor);
Instant before = Instant.now();
BigDecimal result = new BigDecimal(1);
for (long i = 1; i <= factor; i++) {
result = result.multiply(BigDecimal.valueOf(i));
System.out.println("... " + result);
}
Instant after = Instant.now();
long diff = Duration.between(before, after).toMillis();
System.out.println("RESULT: !" + factor + " = " + result);
System.out.println("DURATION: " + diff + " milliseconds");
System.out.println("#####################################################################");
}
}
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.Scanner;
public class RecursiveFactor {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a factorial:");
long factor = in.nextLong();
System.out.println("#####################################################################");
System.out.println("FACTORIAL: !" + factor);
Instant before = Instant.now();
BigDecimal result = factorial(factor);
Instant after = Instant.now();
long diff = Duration.between(before, after).toMillis();
System.out.println("RESULT: !" + factor + " = " + result);
System.out.println("DURATION: " + diff + " milliseconds");
System.out.println("#####################################################################");
}
private static BigDecimal factorial(long factor) {
if (factor == 0) {
return BigDecimal.valueOf(1);
} else {
BigDecimal result = (BigDecimal.valueOf(factor).multiply(factorial(factor - 1)));
System.out.println("... " + result);
return result;
}
}
}
@frekele
Copy link
Author

frekele commented Oct 4, 2019

Online java compiler:
IterativeFactor.java: https://www.jdoodle.com/a/1Amu
RecursiveFactor.java https://www.jdoodle.com/a/1Amv

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment