Advertisement
JeffGrigg

Factorial with double vs BigInteger

Jun 28th, 2018
503
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.82 KB | None | 0 0
  1. import java.math.BigInteger;
  2. import java.text.DecimalFormat;
  3. import java.text.NumberFormat;
  4.  
  5. public class FactorialTest {
  6.  
  7.     private static final NumberFormat formatter = new DecimalFormat("#");
  8.  
  9.     public static void main(String[] args) {
  10.         double fact = 1;
  11.         BigInteger bigFact = new BigInteger("1");
  12.         int i = 0;
  13.         do {
  14.             i++;
  15.  
  16.             fact *= i;
  17.             bigFact = bigFact.multiply(new BigInteger(String.valueOf(i)));
  18.  
  19.             final String bigFormat = bigFact.toString();
  20.             System.out.println(i + " = " + bigFormat);
  21.  
  22.             final String doubleFormat = formatter.format(fact);
  23.             if (!doubleFormat.equals(bigFormat)) {
  24.                 System.out.println("  != " + doubleFormat);
  25.             }
  26.  
  27.         } while (i < 100);
  28.     }
  29.  
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement