Standard libraries
libs5BigNumbersAndMath
- Path
- pkg13libs/libs5BigNumbersAndMath.java
- Package
- pkg13libs
- Study order
- 5
- Run
- Single-file source launch
- Command
- java pkg13libs/libs5BigNumbersAndMath.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg13libs;2 3import java.math.BigDecimal;4import java.math.BigInteger;5import java.math.MathContext;6import java.math.RoundingMode;7 8/*9 * libs5BigNumbersAndMath.java10 * ---------------------------11 * Arbitrary-precision numbers (BigInteger/BigDecimal) and the Math utilities.12 *13 * DEFINITION:14 * BigInteger holds integers of unlimited size; BigDecimal holds exact decimal15 * numbers (no binary floating-point error). Use them for cryptography, money,16 * and anywhere precision matters.17 *18 * KEY POINTS:19 * - double/float are binary and inexact (0.1 + 0.2 != 0.3) — never use for money.20 * - BigDecimal is exact; control scale + RoundingMode explicitly.21 * - BigInteger supports modPow/gcd/isProbablePrime — crypto building blocks.22 * - These types are immutable; operations return new instances.23 */24public class libs5BigNumbersAndMath {25 26 public static void main(String[] args) {27 // The classic floating-point trap28 System.out.println("double 0.1 + 0.2 = " + (0.1 + 0.2) + " <- not 0.3!");29 System.out.println("BigDecimal = " + new BigDecimal("0.1").add(new BigDecimal("0.2")));30 31 // BigInteger: factorial of 50 (overflows long instantly)32 BigInteger fact = BigInteger.ONE;33 for (int i = 1; i <= 50; i++) fact = fact.multiply(BigInteger.valueOf(i));34 System.out.println("\n50! = " + fact);35 36 // BigInteger crypto helpers37 BigInteger a = BigInteger.valueOf(1071), b = BigInteger.valueOf(462);38 System.out.println("\ngcd(1071,462) = " + a.gcd(b));39 System.out.println("2^10 mod 1000 = " + BigInteger.TWO.modPow(BigInteger.TEN, BigInteger.valueOf(1000)));40 System.out.println("is 7919 prime? = " + BigInteger.valueOf(7919).isProbablePrime(20));41 42 // BigDecimal: money math with explicit rounding43 BigDecimal price = new BigDecimal("19.99");44 BigDecimal qty = new BigDecimal("3");45 BigDecimal total = price.multiply(qty).setScale(2, RoundingMode.HALF_UP);46 System.out.println("\n3 x $19.99 = $" + total);47 BigDecimal third = BigDecimal.ONE.divide(new BigDecimal(3), new MathContext(10));48 System.out.println("1/3 (10 digits) = " + third);49 50 // Math utilities51 System.out.println("\nMath.sqrt(2) = " + Math.sqrt(2));52 System.out.println("Math.pow(2,10) = " + Math.pow(2, 10));53 System.out.println("Math.floorMod(-7,3) = " + Math.floorMod(-7, 3));54 System.out.println("Math.addExact OK = " + Math.addExact(2, 3));55 try { Math.addExact(Integer.MAX_VALUE, 1); }56 catch (ArithmeticException e) { System.out.println("addExact overflow caught: " + e.getMessage()); }57 }58}