Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.junit.Rule;
- import org.junit.Test;
- import org.junit.rules.ExpectedException;
- import java.math.BigInteger;
- import static org.junit.Assert.assertEquals;
- import static org.junit.Assert.assertTrue;
- public class FactTest {
- @Rule
- public ExpectedException thrown = ExpectedException.none();
- public static BigInteger factorial(int value) {
- if (value == 1) {
- return BigInteger.valueOf(value);
- } else {
- return BigInteger.valueOf(value).multiply(factorial(value - 1));
- }
- }
- public static BigInteger factorialNonRecursive(int value) {
- if (value == 1) {
- return BigInteger.ONE; // LOL, enterprise code!
- } else {
- BigInteger res = BigInteger.ONE;
- for (int i = 2; i <= value; i++) {
- res = res.multiply(BigInteger.valueOf(i));
- }
- return res;
- }
- }
- @Test
- public void countNonRecursive() {
- assertEquals(BigInteger.valueOf(6L), factorialNonRecursive(3));
- BigInteger largeFrac = factorialNonRecursive(50000);
- // assert that we managed to get very large number
- assertTrue(largeFrac.bitLength() > 700000);
- }
- @Test
- public void count() {
- thrown.expect(StackOverflowError.class);
- assertEquals(BigInteger.ONE, factorial(50000));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment