Guest User

Untitled

a guest
Sep 17th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. import org.junit.Rule;
  2. import org.junit.Test;
  3. import org.junit.rules.ExpectedException;
  4.  
  5. import java.math.BigInteger;
  6.  
  7. import static org.junit.Assert.assertEquals;
  8. import static org.junit.Assert.assertTrue;
  9.  
  10. public class FactTest {
  11. @Rule
  12. public ExpectedException thrown = ExpectedException.none();
  13.  
  14. public static BigInteger factorial(int value) {
  15. if (value == 1) {
  16. return BigInteger.valueOf(value);
  17. } else {
  18. return BigInteger.valueOf(value).multiply(factorial(value - 1));
  19. }
  20. }
  21.  
  22. public static BigInteger factorialNonRecursive(int value) {
  23. if (value == 1) {
  24. return BigInteger.ONE; // LOL, enterprise code!
  25. } else {
  26. BigInteger res = BigInteger.ONE;
  27. for (int i = 2; i <= value; i++) {
  28. res = res.multiply(BigInteger.valueOf(i));
  29. }
  30. return res;
  31. }
  32. }
  33.  
  34. @Test
  35. public void countNonRecursive() {
  36. assertEquals(BigInteger.valueOf(6L), factorialNonRecursive(3));
  37. BigInteger largeFrac = factorialNonRecursive(50000);
  38. // assert that we managed to get very large number
  39. assertTrue(largeFrac.bitLength() > 700000);
  40. }
  41.  
  42. @Test
  43. public void count() {
  44. thrown.expect(StackOverflowError.class);
  45. assertEquals(BigInteger.ONE, factorial(50000));
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment