🧮 Your Math Utility Belt

Common Java Math Methods

Copy, paste, and use these battle-tested utilities for your programs

Last updated:

Get Started in Seconds

Math operations show up everywhere in APCS-A: rounding decimals, finding min/max values, calculating distances, and more. Rather than rewriting these routines every time, copy these proven methods into your driver and test them. Your brain is for solving problems, not retyping math.

Copy-Paste Ready: Click the Copy button, paste into your IDE or JDoodle
Spot the Comments: Read the JavaDoc comments—they explain what the method does
Test and Modify: Copy the driver code first, then add these utilities below

Getting Started: The Driver Code

Use this driver template as your testing workspace. Copy it into JDoodle, then paste math methods below inside the class (but outside the main method). Modify the TODO section to test each utility.

TNTMathUtilDriver.java Java • APCS-A • Setup
    Purpose: Main entry point for testing math utilities Stage: 0 (Initial Testing)
    Formatting Decimal Output with DecimalFormat (Click to expand)

    When your math methods return double values, they often have messy decimals like 3.141592653589793. DecimalFormat is a class that lets you control how many decimal places display, making output clean and readable.

    What is DecimalFormat?

    DecimalFormat is a Java class (from java.text package) that lets you format numbers as strings with a specific number of decimal places. Instead of printing 3.141592653589793, you can format it to show 3.14 for readability.

    How to Use DecimalFormat:

    1. Create a DecimalFormat object: DecimalFormat df = new DecimalFormat("0.00");
    2. Use the format method: df.format(myDouble) returns a formatted string
    3. Print or use the result: System.out.println("Result: " + df.format(result));

    Format String Patterns:

    Pattern Example Result for 3.14159
    "0.00" 2 decimal places (always shows) 3.14
    "0.0" 1 decimal place 3.1
    "0.0000" 4 decimal places 3.1416
    "0" No decimal places (whole number) 3
    "#.##" Up to 2 decimals (omit trailing zeros) 3.14 (or 3.1 if second is 0)

    Example in Context:

    // Without DecimalFormat
    double pi = 3.141592653589793;
    System.out.println("Pi: " + pi);  // Output: Pi: 3.141592653589793
    
    // With DecimalFormat
    DecimalFormat df = new DecimalFormat("0.00");
    System.out.println("Pi: " + df.format(pi));  // Output: Pi: 3.14

    Math Utilities Library

    Browse the utilities below. Click on each one to reveal the code, then copy what you need.

    Type to filter utilities by method name or category •

    Purpose: Round a decimal number to n decimal places

    Example: roundToNearest(3.14159, 2) returns 3.14

    When to Use: Display prices, coordinates, or other values that need precision control

    roundToNearest Java • Static Method

      Purpose: Determine if a number is prime or composite

      Example: isPrime(17) returns true, isPrime(12) returns false

      When to Use: Find prime numbers, validate mathematical properties, cryptography, number analysis

      isPrime Java • Static Method

        Purpose: Extract individual digits from an integer into an array

        Example: extractDigitsWithMath(12345, false) returns [5, 4, 3, 2, 1]

        When to Use: Analyze digit patterns, reverse numbers, validate digit properties, process individual digits

        extractDigitsWithMath Java • Static Method

          Purpose: Extract individual digits from a number using String manipulation instead of math operations

          Example: extractDigitsViaStringManip(12345.6, false) returns [1, 2, 3, 4, 5, 6]

          When to Use: Compare/contrast with math-based approach; handle edge cases like trailing zeros and decimal points

          extractDigitsViaStringManip Java • Static Method

            Purpose: Compare two floating-point numbers safely using a tolerance value

            Example: areAboutEqual(0.1 + 0.2, 0.3, 0.0001) returns true

            When to Use: Compare doubles in conditional logic, avoid == failures due to floating-point precision errors

            areAboutEqual Java • Static Method

              Purpose: Generate repeatable random numbers in a closed interval using the Random class

              Example (int): getRandom(rng, 1, 10) returns a random integer between 1 and 10

              Example (double): getRandom(rng, 0.0, 1.0) returns a random double between 0.0 and 1.0

              When to Use: Generate reproducible random sequences for simulations, games, testing, or seeded randomization

              About the Random Parameter (rng): The rng parameter is a Random object (Random Number Generator). It's the tool that generates pseudo-random numbers.

              • new Random() — Creates a Random object seeded by the system clock. Each time you run your program, you get a different sequence of random numbers (truly unpredictable).
              • new Random(42) — Creates a Random object seeded with a specific number (like 42). Every time you run your program with the same seed, you get the exact same sequence of random numbers (repeatable/reproducible). This is useful for testing and debugging!
              getRandom (Integer Version) Java • Static Method (Overloaded)
                getRandom (Double Version) Java • Static Method (Overloaded)

                  Purpose: Generate random numbers in a closed interval using Math.random() (simpler syntax, no Random object needed)

                  Example (int): getRandom(1, 10) returns a random integer between 1 and 10

                  Example (double): getRandom(0.0, 1.0) returns a random double between 0.0 and 1.0

                  When to Use: Quick random numbers for games, animations, or simple cases where you don't need reproducibility or seed control

                  getRandom (Integer Version) — Math.random() Java • Static Method (Overloaded)
                    getRandom (Double Version) — Math.random() Java • Static Method (Overloaded)

                      Purpose: Generate a collection of n random integers in a closed interval using the Random class

                      Example: generateRandomIntegersIn(rng, 1, 10, 5) returns an ArrayList with 5 random integers, each between 1 and 10

                      When to Use: Create arrays/lists of random data for simulations, testing, shuffling, or populating data structures

                      Note: This method leverages the getRandom(Random rng, int min, int max) helper method for each generated value

                      generateRandomIntegersIn Java • Static Method • Returns ArrayList

                        Purpose: Calculate statistical measures (mean and median) from a collection of integers

                        Example (Mean): calculateMean([1, 2, 3, 4, 5]) returns 3.0 (sum of 15 divided by 5)

                        Example (Median): calculateMedian([3, 1, 4, 1, 5]) returns 3.0 (middle value after sorting: [1, 1, 3, 4, 5])

                        When to Use: Analyze data, find center values, detect outliers, or summarize collections of numbers

                        calculateMean Java • Static Method • Returns double
                          calculateMedian Java • Static Method • Returns double • ⚠️ Sorts ArrayList

                            Purpose: Calculate the median while optionally preserving the original ArrayList's order

                            Example (Preserve): calculateMedian(original, true) returns median and leaves original unchanged

                            Example (Don't Preserve): calculateMedian(original, false) returns median and sorts original (more efficient)

                            When to Use: When you need the median but can't afford to modify the original data, or when efficiency matters and you don't care if the list gets sorted

                            Design Pattern: Method overloading to give callers control over method behavior—a great example of flexible API design!

                            calculateMedian (Overloaded) Java • Static Method • Overloaded • Returns double

                              Purpose: Find the minimum, maximum, and range (max - min) of integers in an ArrayList

                              Example: findExtrema([3, 1, 4, 1, 5], false) returns [1, 5, 4]

                              When to Use: Data analysis, finding outliers, understanding data spread, statistical summaries

                              Returns: An integer array [min, max, range]

                              findExtrema Java • Static Method • Returns int[]

                                Purpose: Find the mode (most frequently occurring value) in an ArrayList

                                Example: findMode([1, 2, 2, 3, 3, 3]) returns [3]

                                Handles Ties: findMode([1, 1, 2, 2, 3]) returns [1, 2] (both appear 2 times)

                                When to Use: Find the most common value in a dataset, detect patterns, identify popular choices

                                Returns: ArrayList of all modes; empty list if no mode exists (all values equally frequent)

                                findMode Java • Static Method • Returns ArrayList<Integer>

                                  Purpose: Get the frequency count of EVERY value in an ArrayList (compare/contrast with findMode)

                                  Example: findModeWithFrequency([1, 2, 2, 3, 3, 3]) returns {1=1, 2=2, 3=3}

                                  When to Use: When you want to see ALL frequency counts, not just the most frequent values; useful for detailed data analysis

                                  Returns: HashMap where key=value and value=frequency count

                                  findModeWithFrequency Java • Static Method • Returns HashMap<Integer, Integer>

                                    Purpose: A reusable class that encapsulates a base and exponent, calculating the power and formatting it for display

                                    Example: TNTPower p = new TNTPower(2, 10); creates 2^10, then p.getValue() returns 1024.0

                                    When to Use: When you need to store, manipulate, and display powers; great for learning object-oriented design and encapsulation

                                    Overloaded Constructors: Default constructor (base=1, exp=0), long version, and int version for flexibility

                                    TNTPower.java Java • Class • Encapsulation • 3 Overloaded Constructors

                                      Purpose: Returns an ArrayList of all prime factors of n (including 1 for n=1), sorted in ascending order

                                      Example: findPrimeFactorsOf(60) returns [2, 2, 3, 5]

                                      When to Use: When you need the complete list of prime factors with repetition; perfect for understanding factorization and building factoring algorithms

                                      Algorithm: Non-recursive method using trial division with prime list optimization for efficiency

                                      findPrimeFactorsOf Java • Static Method • Returns ArrayList<Integer>

                                        Purpose: Returns an ArrayList of TNTPower objects representing consolidated prime factors with elegant Unicode superscripts (e.g., 2², 3¹, 5¹ for 60)

                                        Example: findConsolidatedPrimeFactorsOf(60) returns [2², 3, 5] as TNTPower objects with Unicode superscripts

                                        When to Use: When you need a compact representation of prime factorization; perfect for displaying prime powers and factorization analysis

                                        Algorithm: Uses findPrimeFactorsOf() then consolidates duplicates into TNTPower objects

                                        findConsolidatedPrimeFactorsOf Java • Static Method • Returns ArrayList<TNTPower>

                                          Purpose: Calculate logarithms with any base using the Change of Base formula: log_b(x) = log(x) / log(b)

                                          Example (Base 10): logBase10(100) returns 2.0

                                          Example (Custom Base): logBaseB(8, 2) returns 3.0 (since 2³ = 8)

                                          When to Use: Scientific calculations, exponential decay/growth analysis, decibel calculations, information theory (bits), algorithmic complexity analysis (Big-O)

                                          logBase10 & logBaseB Java • Static Methods • Returns double • Logarithms

                                            Purpose: Calculate n! = n × (n-1) × (n-2) × ... × 1 using long for larger values, with safety check for Long.MAX_VALUE overflow

                                            Example: longFactorial(5) returns 120L

                                            Special Cases: longFactorial(0) and longFactorial(1) both return 1

                                            When to Use: Permutations, combinations, probability calculations, binomial coefficients, counting problems

                                            longFactorial Java • Static Method • Returns long • Combinatorics

                                              Purpose: Extract the fractional (decimal) part of a double value using Math.floor(), avoiding string manipulation

                                              Example: getFractionalPart(5.75) returns 0.75

                                              Example: getFractionalPart(-3.42) returns -0.42 (preserves sign)

                                              When to Use: Separating integer and decimal parts, verifying fractional precision, pixel positioning (screen coordinates), financial calculations

                                              getFractionalPart Java • Static Method • Returns double • Math

                                                Purpose: Find the largest factor of n that is less than or equal to √n, useful for creating square-like matrices

                                                Example: findFactorClosestToSquareRoot(60) returns 6 (since 6 × 10 = 60, and 6 is the larger of the two balanced factors)

                                                Special Case: findFactorClosestToSquareRoot(100) returns 10 (perfect square)

                                                When to Use: Creating 2D arrays/matrices with nearly square dimensions, optimal grid layouts, container sizing

                                                findFactorClosestToSquareRoot Java • Static Method • Returns int • Factorization

                                                  Purpose: Find the smallest perfect square that is greater than the given value

                                                  Example: findFirstPerfectSquareLargerThan(24) returns 25.0 (5²)

                                                  Example: findFirstPerfectSquareLargerThan(100) returns 121.0 (11²)

                                                  When to Use: Rounding up to perfect squares, array sizing, pagination calculations, boundary computations

                                                  findFirstPerfectSquareLargerThan Java • Static Method • Returns double • Perfect Squares

                                                    Purpose: Calculate the Greatest Common Factor (GCF/GCD) of two numbers using the Euclidean algorithm

                                                    Example: calculateGCF(60, 48) returns 12 (largest number dividing both)

                                                    Example: calculateGCF(17, 19) returns 1 (primes are coprime)

                                                    When to Use: Fraction simplification, ratio calculations, finding common divisors, music beat synchronization, cryptography

                                                    calculateGCF (Two Overloads) Java • Static Method • Returns int/long • Number Theory

                                                      Purpose: A custom class that represents and simplifies radicals (square roots) in the form: coefficient·√(radicand). Automatically simplifies to lowest radical form.

                                                      Example: TNTRadical(2, 72) simplifies to 12·√2 (since 72 = 36×2, and √36 = 6, so 2×6 = 12)

                                                      Key Methods: Constructor, toString(), getRadicand(), getCoeff(), simplify(), factor(), isPrime(), consolidate()

                                                      When to Use: Radical arithmetic, geometry problems with irrational numbers, algebraic expressions, test preparation, mathematical accuracy in calculations

                                                      TNTRadical Class Java • Custom Class • Radical Simplification

                                                        Purpose: Two complementary methods for analyzing digits: countDigits() counts total digits using arithmetic (no string conversion), while countUniqueDigits() counts how many different digit values appear. Both handle negative numbers and work with int and long.

                                                        Examples: countDigits(1223334) returns 7 (total digits); countUniqueDigits(1223334) returns 4 (unique digits: 1,2,3,4)

                                                        Overloads: Both methods have `(int n)` and `(long n)` versions for flexibility

                                                        When to Use: Input validation, digit-based algorithms, number property analysis, checking for repeated digits, competition programming, number pattern detection

                                                        countDigits Methods Java • Overloaded Methods • Digit Counting

                                                          Purpose: Tests whether a number is even (divisible by 2). Returns a boolean using the modulo operator. Both int and long versions available. This utility teaches an important code simplification pattern—replacing verbose if-else with direct boolean expressions.

                                                          Examples: isEven(42) returns true; isEven(43) returns false; isEven(-8) returns true

                                                          Overloads: Both methods have `(int n)` and `(long n)` versions

                                                          When to Use: Loop control, algorithm branching (even/odd handling), data classification, number properties analysis, parity validation

                                                          isEven Methods Java • Boolean Test • Parity Check

                                                            Purpose: Two complementary methods for base conversion: convertFromBaseTenToBaseB() converts decimal (base 10) to any base 2-9 using the "dibble-dabble" algorithm, while convertFromBaseTenToHex() converts to hexadecimal (base 16) using Java's built-in Integer.toHexString(). Both return formatted strings with subscript notation (e.g., 42₁₀ = 101010₂).

                                                            Examples: convertFromBaseTenToBaseB(42, 2) returns "(101010)₂"; convertFromBaseTenToHex(255) returns "(FF)₁₆"

                                                            Algorithms: Dibble-dabble uses repeated division and remainder extraction; hexadecimal uses built-in Java conversion

                                                            When to Use: Understanding number systems, CS fundamentals, hexadecimal color codes, binary representation, algorithm study, educational demonstrations

                                                            Base Conversion Methods Java • Number Systems • Base Conversion

                                                              Purpose: Two overloaded methods for calculating remainders using the mathematical definition: remainder = numerator - (quotient × denominator). These methods exist because Java's modulus operator % has significant limitations: it doesn't work with floating-point numbers, and in certain situations, the mathematical definition is more reliable or clearer. These are legacy utilities from base conversion and hexadecimal conversion GUI tools (2003).

                                                              Examples: getRemainder(42L, 5) returns 2; getRemainder(42L, 5.0) also returns 2; getRemainder(1000000000L, 7) handles large numbers reliably

                                                              When to Use: Working with floating-point divisors, hexadecimal/base conversion algorithms, situations where explicit calculation is clearer than %, handling edge cases with large numbers

                                                              getRemainder Methods Java • Modular Arithmetic • Base Conversion Legacy

                                                                Purpose: Two methods that convert integers from base 10 to ANY base from 2-36 using Java's built-in Integer.toString(int, radix). This is the simplest and most practical approach for real-world use. Supports all bases: binary (2), octal (8), decimal (10), hexadecimal (16), and any custom base up to 36 (using 0-9 and A-Z). The uppercase variant formats results with capital letters for bases > 10.

                                                                Examples: convertToBaseUsingBuiltIn(42, 2) returns "101010"; convertToBaseBuiltInUppercase(255, 16) returns "FF"; convertToBaseUsingBuiltIn(42, 36) returns "16"

                                                                When to Use: Production code, any base conversion task, when you need clean and efficient code, when you want to contrast with the educational dibble-dabble approach

                                                                Base Conversion Using Built-In Methods Java • Built-In • Practical Implementation

                                                                  Purpose: Calculates the Least Common Multiple (LCM) of two integers. The LCM is the smallest positive integer that is divisible by both input numbers. This method uses the mathematical relationship: LCM(a, b) = (a × b) / GCF(a, b). It depends on the calculateGCF() method, demonstrating how powerful utilities compose together.

                                                                  When to Use: Finding common denominators in fractions, scheduling problems, synchronizing cycles, GCD/LCM math problems, number theory applications

                                                                  Examples: calculateLCM(12, 18) returns 36; calculateLCM(4, 6) returns 12; calculateLCM(7, 11) returns 77 (coprime numbers: LCM = product)

                                                                  calculateLCM Java • Number Theory • Composite Method

                                                                    Download Complete Utility Library

                                                                    All 29 utilities plus two support classes — ready to use in your projects.

                                                                    TNTMath.java TNTPower.java TNTRadical.java

                                                                    📦 TNTMath.java

                                                                    Methods: 37 overloads (29 utilities)
                                                                    Size: ~33 KB
                                                                    Contains: All 29 math utilities, logically organized and searchable

                                                                    Use this for all your math method needs: GCF, LCM, mean, median, factorization, base conversion, and more.

                                                                    ⚡ TNTPower.java

                                                                    Class: Support for base^exponent
                                                                    Size: ~4 KB
                                                                    Features: Unicode superscripts for single digits, caret notation for large exponents

                                                                    Used by TNTMath's findConsolidatedPrimeFactorsOf() to elegantly display prime factorizations like 2³ × 5².

                                                                    √ TNTRadical.java

                                                                    Class: Simplified radical expressions
                                                                    Size: ~9 KB
                                                                    Features: Automatic perfect square extraction, exact/approximate results

                                                                    Simplifies radicals like √300 → 10√3, with both mathematical symbols and numerical approximation.

                                                                    📋

                                                                    How to Use These Utilities

                                                                    1. Download: Click one of the download buttons above to get the files you need
                                                                    2. Add to Your Project: Place the .java file(s) in your project folder or in JDoodle
                                                                    3. Import or Use Directly: If in same package, use TNTMath.calculateGCF() directly; if separate, add import statements
                                                                    4. Test It: Copy a utility call into your code and test with example inputs
                                                                    5. Modify & Extend: Customize the methods to suit your needs