Copy, paste, and use these battle-tested utilities for your programs
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.
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.
The driver code includes four essential imports at the top:
import java.util.ArrayList; — Required for methods that use ArrayListimport java.util.Random; — Required for methods that use the Random classimport java.util.Collections; — Required for Collections.sort() (used in median calculation)import java.text.DecimalFormat; — Required for pretty-printing decimal numbersIf you forget these imports, you'll get compiler errors! The driver code has them ready to go—just copy and paste the whole thing into JDoodle.
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:
DecimalFormat df = new DecimalFormat("0.00");df.format(myDouble) returns a formatted stringSystem.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
When you call df.format(myDouble), it does NOT change the original value.
It returns a new String with the formatted representation. The original double
value stays exactly as it was (with all those decimal places).
You use the returned string for display only—not for calculations.
Browse the utilities below. Click on each one to reveal the code, then copy what you need.
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
Math.round() to round to nearest integerPurpose: 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
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
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
("" + n).toCharArray()) preserves digit orderPurpose: 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
Math.abs(tol) ensures tolerance is positiveDouble.MIN_NORMAL (2.225E-308)Math.abs(x - y) < tol0.1 + 0.2 == 0.3 returns FALSE (due to binary representation)areAboutEqual(0.1 + 0.2, 0.3, 0.0001) returns TRUEPurpose: 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!Math.min() and Math.max()max - minrng.nextInt(range + 1) to get random value in [0, range]min + random_valueMath.min() and Math.max()Math.ulp(range) to include boundary precision
Math.ulp()? ULP stands for "Unit in the Last Place"—it's the smallest difference Java can represent between two double values. When generating random doubles, adding Math.ulp(range) ensures the maximum value is included as a possible result (instead of being just barely out of reach).rng.nextDouble() returns [0.0, 1.0)min + adjustedRange * nextDouble()Math.ulp() for precise boundary handlingPurpose: 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
Math.min() and Math.max()max - minMath.random() returns [0.0, 1.0) — a value between 0.0 and 1.0min + adjustedRange * Math.random()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
ArrayList<Integer> to hold resultsn times, calling getRandom(rng, min, max) each iterationgetRandom() helper (DRY principle — Don't Repeat Yourself)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
Collections.sort(aL)
ArrayList<Integer> copy = new ArrayList<>(original); double med = calculateMedian(copy);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!
if(shouldPreserveOriginal) — make a copy of the list; otherwise use the originalCollections.sort(data))calculateMedian(aL) — Modifies original (destructive, but efficient)calculateMedian(aL, true) — Preserves original (creates a copy, slight overhead)calculateMedian(aL, false) — Same as single-parameter version (most efficient)calculateMedian but different signatures (parameter lists)calculateMedian(list) OR calculateMedian(list, true/false)shouldPreserveOriginal = false — Faster (no copy made)shouldPreserveOriginal = true — Safer (original data protected), slightly slower due to copyPurpose: 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]
[0, 0, 0] if empty)max - min[min, max, range]shouldPreserveOriginal = false — Faster (no copy made), modifies originalshouldPreserveOriginal = true — Safer (original data protected), creates a copyint[] stats = findExtrema(scores, false);System.out.println("Min: " + stats[0] + ", Max: " + stats[1] + ", Range: " + stats[2]);// Output: Min: 65, Max: 98, Range: 33Purpose: 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)
ArrayList<Integer> modes = findMode(temperatures);if(modes.isEmpty()) System.out.println("No mode found");else System.out.println("Mode(s): " + modes);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
HashMap<Integer, Integer> freq = findModeWithFrequency(data);System.out.println("Value 3 appears " + freq.get(3) + " times");for(Integer value : freq.keySet()) System.out.println(value + ": " + freq.get(value));map.getOrDefault(key, 0) — Get value OR return 0 if key doesn't exist (clever!)map.keySet() — Get all unique keys (values in our case)map.values() — Get all frequency countsPurpose: 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() — Default: base=1, exponent=0 (value=1)TNTPower(long b, long x) — Full constructor with long parametersTNTPower(int b, int x) — Overloaded int version for conveniencegetBase(), getExponent(), getValue()findPowerDecomposition(long n) Static Utility Method: Given a number n, finds the largest base b such that n = b^x.findSmallestBasePowerDecomposition(long n) Static Utility Method: Given a number n, finds the smallest base b such that n = b^x. (Sister method: finds the inverse decomposition!) Math.pow(base, exponent) to calculate the valuetoString() method displays the power nicely, showing "base^exp" formatfindPowerDecomposition(n) to find the largest base representation of a perfect powerfindSmallestBasePowerDecomposition(n) to find the smallest base representation of a perfect power// Create a TNTPower object
TNTPower p1 = new TNTPower(2, 3);
System.out.println("2^3 = " + p1.getValue()); // Output: 2^3 = 8.0
System.out.println(p1.toString()); // Output: 2³ (Unicode superscript!)
// Large exponent uses caret notation for clarity
TNTPower p2 = new TNTPower(2, 15);
System.out.println(p2.toString()); // Output: 2^15
// Find power decomposition
TNTPower result = TNTPower.findPowerDecomposition(64);
if (result != null) {
System.out.println("64 = " + result.getBase() + "^" + result.getExponent());
// Output: 64 = 8^2 (largest base!)
}
// Use in an ArrayList (great for factoring!)
ArrayList<TNTPower> factors = new ArrayList<>();
factors.add(new TNTPower(2, 2)); // 2^2 = 4
factors.add(new TNTPower(3, 1)); // 3^1 = 3
factors.add(new TNTPower(5, 1)); // 5^1 = 5
// Together: 4 × 3 × 5 = 60
// Iterate and display
for(TNTPower p : factors) {
System.out.println(p.toString() + " = " + p.getValue());
}
// Find power decomposition with smallest base
TNTPower smallestBase = TNTPower.findSmallestBasePowerDecomposition(64);
if (smallestBase != null) {
System.out.println("64 = " + smallestBase.getBase() + "^" + smallestBase.getExponent());
// Output: 64 = 2^6 (smallest base!)
}
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
// Find prime factors of 60
ArrayList<Integer> factors = findPrimeFactorsOf(60);
System.out.println(factors); // Output: [2, 2, 3, 5]
// Find prime factors of 100
ArrayList<Integer> factors100 = findPrimeFactorsOf(100);
System.out.println(factors100); // Output: [2, 2, 5, 5]
// Find prime factors of 1
ArrayList<Integer> factorsOne = findPrimeFactorsOf(1);
System.out.println(factorsOne); // Output: [1]
// Loop through and display
ArrayList<Integer> factors = findPrimeFactorsOf(60);
for(int factor : factors) {
System.out.print(factor + " ");
}
// Output: 2 2 3 5
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
// Find consolidated prime factors of 60
ArrayList<TNTPower> factors = findConsolidatedPrimeFactorsOf(60);
for(TNTPower p : factors) {
System.out.println(p.toString() + " = " + p.getValue());
}
// Output (with elegant Unicode superscripts for small exponents):
// 2² = 4.0
// 3 = 3.0
// 5 = 5.0
// Use in calculations (product should equal original)
long product = 1;
for(TNTPower p : factors) {
product *= (long) p.getValue();
}
System.out.println("Original: 60, Product: " + product); // Both 60
// Find consolidated factors of 1000
ArrayList<TNTPower> factors1000 = findConsolidatedPrimeFactorsOf(1000);
for(TNTPower p : factors1000) {
System.out.println(p.toString());
}
// Output: 2^3, 5^3 (since 1000 = 8 × 125 = 2^3 × 5^3)
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)
// Information Theory: How many bits for 256 values?
double bitsNeeded = logBaseB(256, 2); // 8.0 (since 2^8 = 256)
// pH calculation in chemistry uses log₁₀
double pH = -logBase10(1e-7); // pH = 7.0 for neutral solution
// Decibels: dB = 10 × log₁₀(ratio)
double intensity_ratio = 100;
double decibels = 10 * logBase10(intensity_ratio); // 20 dB
// Algorithm complexity: How many times to divide n by 2?
int n = 1024;
int halvings = (int)logBaseB(n, 2); // 10 halvings to reach 1
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
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
// Separate integer and decimal parts
double num = 5.75;
long integerPart = (long)num;
double fractionalPart = getFractionalPart(num);
System.out.println(integerPart + " + " + fractionalPart); // Output: 5 + 0.75
// Verify fractional precision
double value = 0.1 + 0.2; // Floating point: 0.30000000000000004
double frac = getFractionalPart(value);
System.out.println(frac); // Shows actual fractional representation
// Pixel positioning (sub-pixel rendering)
double screenX = 123.456;
double subPixelOffset = getFractionalPart(screenX);
System.out.println("Pixel: " + (long)screenX + ", Offset: " + subPixelOffset);
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
// Store 60 items in a nearly-square matrix
int n = 60;
int height = findFactorClosestToSquareRoot(n); // 6
int width = n / height; // 10
System.out.println("Matrix: " + height + " x " + width); // 6 x 10 (balanced!)
// Square case: 100 items
int n2 = 100;
int dim = findFactorClosestToSquareRoot(n2); // 10
System.out.println("Perfect square: " + dim + " x " + dim); // 10 x 10
// Another example: 48 items
int n3 = 48;
int h3 = findFactorClosestToSquareRoot(n3); // 6
int w3 = n3 / h3; // 8
System.out.println("Matrix: " + h3 + " x " + w3); // 6 x 8
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
// Array sizing: allocate extra space for growth
int currentSize = 50;
double nextBoundary = findFirstPerfectSquareLargerThan(currentSize); // 64.0
int[] expandedArray = new int[(int)nextBoundary];
// Perfect square check: 24 → 25, 100 → 121
System.out.println(findFirstPerfectSquareLargerThan(24)); // 25.0 (5²)
System.out.println(findFirstPerfectSquareLargerThan(100)); // 121.0 (11²)
// Edge case: exact perfect square
System.out.println(findFirstPerfectSquareLargerThan(25)); // 36.0 (not 25; strictly larger!)
// Large number example
System.out.println(findFirstPerfectSquareLargerThan(1000)); // 1024.0 (32²)
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
// Fraction simplification
int numerator = 60, denominator = 48;
int gcf = calculateGCF(numerator, denominator); // 12
System.out.println(numerator/gcf + "/" + denominator/gcf); // Output: 5/4 (simplified!)
// Finding common beat in music: LCM = (a*b)/GCF
int bpm1 = 120, bpm2 = 160;
int gcf2 = calculateGCF(bpm1, bpm2); // 40
int lcm = (bpm1 * bpm2) / gcf2; // 480
// Coprime numbers (no common factors except 1)
System.out.println(calculateGCF(17, 19)); // 1 (both prime)
// Step-by-step: calculateGCF(60, 48)
// Step 1: rem = 60 mod 48 = 12; n1=48, n2=12
// Step 2: rem = 48 mod 12 = 0; gcf = 12
// Answer: 12 ✓
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(2, 72) → Simplify:
// Step 1: Factor radicand: 72 = [2, 2, 2, 3, 3]
// Step 2: Consolidate: [2³, 3²]
// Step 3: Extract perfect squares:
// - 2³: exponent is odd, extract 2^(3-1)/2 = 2¹ = 2
// - 3²: exponent is even, extract 3^(2/2) = 3¹ = 3
// - Total extracted: 2 × 3 = 6
// Step 4: Update values:
// - coeff = 2 × 6 = 12
// - radicand = 72 / (6²) = 72 / 36 = 2
// Result: 12·√2 (original: 2·√72)
// Decimal: 12 × √2 ≈ 16.97
✅ Example Usage Scenarios
// Basic simplification (irrational result with approximation)
TNTRadical r1 = new TNTRadical(1, 50);
System.out.println(r1); // 1·√(50) = 5·√(2) ≈ 7.071
// With coefficient (simplification + approximation)
TNTRadical r2 = new TNTRadical(6, 300);
System.out.println(r2); // 6·√(300) = 60·√(3) ≈ 103.923
// Perfect square (exact value - no approximation)
TNTRadical r3 = new TNTRadical(1, 36);
System.out.println(r3); // 1·√(36) = 6
// Already simplified radical (no change)
TNTRadical r4 = new TNTRadical(5, 7);
System.out.println(r4); // 5·√(7) ≈ 13.229
// Geometry application: diagonal of rectangle
double width = 3, height = 4;
long radicandSq = (long)(width*width + height*height); // 25
TNTRadical diagonal = new TNTRadical(1, radicandSq);
System.out.println("Diagonal: " + diagonal); // 1·√(25) = 5
// Using helper methods
ArrayList<Long> factors = TNTRadical.factor(60); // [2,2,3,5]
boolean isPrimeCheck = TNTRadical.isPrime(17); // true
✅ Related Utilities
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
// Example: countDigits(12345)
// Step 1: n = 12345, count = 0
// Step 2: n = 1234, count = 1 (12345 / 10 = 1234)
// Step 3: n = 123, count = 2 (1234 / 10 = 123)
// Step 4: n = 12, count = 3 (123 / 10 = 12)
// Step 5: n = 1, count = 4 (12 / 10 = 1)
// Step 6: n = 0, count = 5 (1 / 10 = 0, loop ends)
// Result: 5 digits ✓
// Negative number example: countDigits(-42)
// Math.abs(-42) = 42, then same as above: count = 2 ✓
✅ How countUniqueDigits Algorithm Works
// Example: countUniqueDigits(1223334)
// Start: n = 1223334, uniqueDigits = {}
// Step 1: 1223334 % 10 = 4, add to set: {4}, n = 122333
// Step 2: 122333 % 10 = 3, add to set: {3,4}, n = 12233
// Step 3: 12233 % 10 = 3, try to add: {3,4} (already there), n = 1223
// Step 4: 1223 % 10 = 3, try to add: {3,4} (already there), n = 122
// Step 5: 122 % 10 = 2, add to set: {2,3,4}, n = 12
// Step 6: 12 % 10 = 2, try to add: {2,3,4} (already there), n = 1
// Step 7: 1 % 10 = 1, add to set: {1,2,3,4}, n = 0
// Result: 4 unique digits ✓
✅ Example Usage Scenarios
// ═══ countDigits Examples ═══
int digits1 = countDigits(42); // 2
int digits2 = countDigits(1000); // 4
int digits3 = countDigits(-12345); // 5 (ignores minus)
long digits4 = countDigits(9876543210L); // 10
// Input validation
if(countDigits(567) == 3){
System.out.println("Three-digit number!");
}
// ═══ countUniqueDigits Examples ═══
int unique1 = countUniqueDigits(42); // 2 (digits: 4, 2)
int unique2 = countUniqueDigits(1223334); // 4 (unique: 1, 2, 3, 4)
int unique3 = countUniqueDigits(111222); // 2 (unique: 1, 2)
int unique4 = countUniqueDigits(9876543210L); // 10 (all digits appear!)
int unique5 = countUniqueDigits(-555); // 1 (only digit 5)
// Finding "pandigital-like" numbers (all unique digits)
long num = 9876543210L;
if(countUniqueDigits(num) == countDigits(num)){
System.out.println("All digits are unique!");
}
// Detecting repeated digits
int input = 1223334;
if(countUniqueDigits(input) < countDigits(input)){
System.out.println("Has repeated digits!"); // true
}
✅ Related Utilities
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
// ═══ VERBOSE VERSION (What beginners write) ═══
public static boolean isEvenVerbose(int x){
if(x % 2 == 0){
return true;
} else {
return false;
}
}
// ═══ SIMPLIFIED VERSION (What experienced programmers write) ═══
public static boolean isEven(int x){
return x % 2 == 0;
}
// Both do EXACTLY the same thing!
// The simplified version is preferred because:
// 1. Cleaner to read
// 2. Less code to maintain
// 3. Same performance
// 4. Shows understanding of boolean logic
✅ Example Usage Scenarios
// Basic parity test
if(isEven(42)){
System.out.println("42 is even"); // prints
}
// Filtering in loops
int[] numbers = {1, 2, 3, 4, 5, 6};
for(int num : numbers){
if(isEven(num)){
System.out.println(num + " is even");
}
}
// Output: 2 is even, 4 is even, 6 is even
// Counting even numbers
int[] data = {10, 15, 20, 25, 30};
int evenCount = 0;
for(int x : data){
if(isEven(x)) evenCount++;
}
System.out.println("Even numbers: " + evenCount); // 3
// Using with long
long largeNum = 1000000000L;
if(isEven(largeNum)){
System.out.println("Large number is even");
}
// Negative numbers work too
System.out.println(isEven(-8)); // true (even)
System.out.println(isEven(-7)); // false (odd)
// Generating even/odd sequences
System.out.println("Even numbers 1-10:");
for(int i = 1; i <= 10; i++){
if(isEven(i)){
System.out.print(i + " ");
}
}
// Output: Even numbers 1-10: 2 4 6 8 10
✅ Related Utilities
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
// Convert 42₁₀ to binary (base 2)
// Using Dibble-Dabble (repeated division)
Step 1: 42 ÷ 2 = 21 remainder 0
Step 2: 21 ÷ 2 = 10 remainder 1
Step 3: 10 ÷ 2 = 5 remainder 0
Step 4: 5 ÷ 2 = 2 remainder 1
Step 5: 2 ÷ 2 = 1 remainder 0
Step 6: 1 ÷ 2 = 0 remainder 1 (STOP when quotient = 0)
Read remainders BOTTOM-TO-TOP: 101010
Result: 42₁₀ = 101010₂ ✓
// Another example: 42₁₀ to octal (base 8)
Step 1: 42 ÷ 8 = 5 remainder 2
Step 2: 5 ÷ 8 = 0 remainder 5 (STOP)
Read remainders BOTTOM-TO-TOP: 52
Result: 42₁₀ = 52₈ ✓
✅ Why Subscript Notation?
// Better notation makes math clearer:
❌ Confusing: (101010)base-2 or (101010)base2
✅ Clear: 101010₂ (subscript shows base)
✅ Standard: (101010)₂ (with parentheses in formal notation)
Examples in mathematical notation:
• 42₁₀ = decimal form (base 10)
• 101010₂ = binary form (base 2)
• 52₈ = octal form (base 8)
• FF₁₆ = hexadecimal form (base 16)
The subscript is the base; makes it obvious at a glance!
✅ Example Usage Scenarios
// ═══ Base Conversion Examples ═══
// Convert to various bases
String bin = convertFromBaseTenToBaseB(42, 2); // "(101010)₂"
String oct = convertFromBaseTenToBaseB(42, 8); // "(52)₈"
String base3 = convertFromBaseTenToBaseB(42, 3); // "(1120)₃"
// Print results
System.out.println(bin); // (101010)₂
System.out.println(oct); // (52)₈
System.out.println(base3); // (1120)₃
// ═══ Hexadecimal Conversion Examples ═══
// Colors in web design often use hex
String red = convertFromBaseTenToHex(255); // "(FF)₁₆"
String green = convertFromBaseTenToHex(128); // "(80)₁₆"
String blue = convertFromBaseTenToHex(64); // "(40)₁₆"
System.out.println("Red in hex: " + red); // (FF)₁₆
System.out.println("Green in hex: " + green); // (80)₁₆
System.out.println("Blue in hex: " + blue); // (40)₁₆
// ═══ Validation and Error Handling ═══
// Invalid base (outside 2-9) returns base-10 form
String invalid = convertFromBaseTenToBaseB(100, 15); // "(100)₁₀" (error case)
// Valid bases are 2 through 9
for(int base = 2; base <= 9; base++){
System.out.println("42 in base " + base + ": "
+ convertFromBaseTenToBaseB(42, base));
}
// Output:
// 42 in base 2: (101010)₂
// 42 in base 3: (1120)₃
// 42 in base 4: (222)₄
// 42 in base 5: (132)₅
// 42 in base 6: (110)₆
// 42 in base 7: (60)₇
// 42 in base 8: (52)₈
// 42 in base 9: (46)₉
✅ Related Utilities
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
42.5 % 3.0, you'll get a compile error. The mathematical definition always works.remainder = num - quotient * denom notation—it makes the algorithm visible and testable.42 % 5 and getRemainder(42L, 5) both return 242.5 % 3.0 → COMPILE ERROR ✗ | getRemainder(42L, 3.0) → 2 ✓getRemainder(1000000000L, 7) = 1000000000 - (142857142 × 7) = 6getRemainder(42L, 5.0) = 42 - (8 × 5.0) = 2 (as long)// ═══ Modulus Operator Limitations ═══
// ✅ Works: integers with %
int result1 = 42 % 5; // 2 (works fine)
long result2 = 1000000L % 7; // 6 (also works)
// ❌ FAILS: floats/doubles with % (COMPILE ERROR)
// double result3 = 42.5 % 3.0; // ILLEGAL! % undefined for floating-point
// long result4 = 1000L % 3.5; // ILLEGAL! Same reason
// ✅ Works: Mathematical definition handles all cases
int r1 = getRemainder(42L, 5); // 2 ✓
long r2 = getRemainder(1000000L, 7L); // 6 ✓
long r3 = getRemainder(42L, 3.5); // 1 ✓ (the one case % can't do!)
// The mathematical definition is universal:
// remainder = numerator - (quotient × denominator)
✅ Detailed Algorithm Walkthrough
// ═══ getRemainder(42L, 5) Step-by-Step ═══
Step 1: q = 42 / 5 = 8 (integer division)
Step 2: remainder = 42 - (8 × 5) = 42 - 40 = 2
Result: 2 ✓ (same as 42 % 5)
// ═══ getRemainder(1000000L, 7) with Large Numbers ═══
Step 1: q = 1000000 / 7 = 142857 (integer division)
Step 2: remainder = 1000000 - (142857 × 7)
Step 3: remainder = 1000000 - 999999 = 1
Result: 1 ✓ (reliable even with large numbers)
// ═══ getRemainder(42L, 5.0) with Floating-Point Divisor ═══
Step 1: q = (double)(42L) / 5.0 = 42.0 / 5.0 = 8.4
Step 2: Convert q back to long: (long)8.4 = 8
Step 3: remainder = 42 - (8 × 5.0) = 42 - 40 = 2
Result: 2 ✓ (% can't do this at all!)
// ═══ Base Conversion Application ═══
// Extract digits using remainder calculation
int number = 42;
int base = 2;
String binary = "";
while(number > 0){
int digit = getRemainder(number, base); // Gets last digit
binary = digit + binary;
number = number / base; // Move to next digit
}
// Result: binary = "101010" (which is 42₂)
✅ Example Usage Scenarios
// ═══ Using getRemainder(long, int) ═══
// Scenario 1: Extract digits from a large number
long num = 1234567890L;
int remainder = getRemainder(num, 10); // Last digit: 0
System.out.println("Last digit: " + remainder); // 0
// Scenario 2: Check divisibility by testing remainder
long bigNum = 1000000000L;
if(getRemainder(bigNum, 7) == 0){
System.out.println("Divisible by 7!");
} else {
System.out.println("Remainder: " + getRemainder(bigNum, 7)); // 1
}
// ═══ Using getRemainder(long, double) ═══
// Scenario 1: Remainder with decimal divisor
long numerator = 42L;
double divisor = 5.0;
long result = getRemainder(numerator, divisor); // 2
// Scenario 2: Flexible base conversion (non-integer bases)
long value = 100L;
double base = 3.5;
long remainder = getRemainder(value, base); // 1
System.out.println("100 ÷ 3.5 = " + (value / base) +
" remainder " + remainder);
// ═══ Base Conversion Using getRemainder ═══
// Convert 42 to binary using this method
int n = 42;
String binary = "";
while(n > 0){
binary = getRemainder(n, 2) + binary;
n = n / 2;
}
System.out.println("42 in binary: " + binary); // 101010
// Convert 255 to hex using this method
int hex_num = 255;
String hex = "";
int[] hexDigits = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
String[] hexChars = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
while(hex_num > 0){
hex = hexChars[(int)getRemainder(hex_num, 16)] + hex;
hex_num = hex_num / 16;
}
System.out.println("255 in hex: " + hex); // FF
✅ When to Use This vs. %
// Use % (modulus operator) when:
int a = 42 % 5; // ✓ Simple integer remainder, % is cleaner
long b = 1000L % 7; // ✓ Integer arithmetic only
// Use getRemainder() when:
long c = getRemainder(42L, 5); // ✓ Explicit algorithm visibility
long d = getRemainder(42L, 5.0); // ✓ REQUIRED: floating-point divisor
long e = getRemainder(bigNum, 7); // ✓ Teaching base conversion concept
// double f = 42.5 % 3.0; // ✗ COMPILE ERROR—use getRemainder!
long f = getRemainder(42L, 3.5); // ✓ Works with decimal divisor
✅ Related Utilities
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
Integer.toString(number, radix)convertToBaseUsingBuiltIn(42, 16) → "2a"convertToBaseBuiltInUppercase(255, 16) → "FF"// ═══ COMPARING ALL THREE APPROACHES ═══
int number = 42;
// ═══ Approach 1: Dibble-Dabble (Educational - Utility 26) ═══
// Use: Learn HOW base conversion works
String result1 = convertFromBaseTenToBaseB(42, 2); // "(101010)₂"
// Pros: See every step, understand the algorithm
// Cons: Only bases 2-9, more code, slower
// Lines of code: ~15
// ═══ Approach 2: Built-In Hex (Specialized - Utility 26) ═══
// Use: Convert to hexadecimal specifically
String result2 = convertFromBaseTenToHex(42); // "(2A)₁₆"
// Pros: Optimized for hex, one line, formatted nicely
// Cons: Only hexadecimal (base 16)
// Lines of code: 2
// ═══ Approach 3: Universal Built-In (Practical - Utility 28) ⭐ ═══
// Use: ANY base conversion in real code
String result3a = convertToBaseUsingBuiltIn(42, 2); // "101010"
String result3b = convertToBaseUsingBuiltIn(42, 8); // "52"
String result3c = convertToBaseUsingBuiltIn(42, 16); // "2a"
String result3d = convertToBaseUsingBuiltIn(42, 36); // "16"
// Pros: Universal (all bases), clean, fast, production-ready
// Cons: Less "see how it works" transparency
// Lines of code: 1 (after wrapping error check)
// Summary for 42 → various bases:
// Base 2: "101010" (all three work, but Approach 1 shows the algorithm)
// Base 8: "52" (Approaches 2 & 3 work; Approach 1 works too)
// Base 16: "2A" (all three work; Approach 2 nicely formatted)
// Base 36: "16" (ONLY Approach 3 works!)
✅ Detailed Algorithm Walkthrough
// ═══ How Integer.toString(int, radix) Works ═══
// Java's implementation is optimized but equivalent to this concept:
// Step 1: Convert 42 to binary (base 2)
Integer.toString(42, 2)
// Internally does something like:
// - Extract digits using mod and div (like dibble-dabble)
// - For bases 2-10: use digits 0-9
// - For bases 11-36: use digits 0-9, then A-Z
// Result: "101010"
// Step 2: Convert 255 to hexadecimal (base 16)
Integer.toString(255, 16)
// - 255 ÷ 16 = 15 remainder 15 (15 = 'F')
// - 15 ÷ 16 = 0 remainder 15 (15 = 'F')
// - Read backwards: FF
// Result: "ff" (lowercase)
// Step 3: Uppercase version
Integer.toString(255, 16).toUpperCase()
// Result: "FF"
// Step 4: Exotic base (base 36)
Integer.toString(42, 36)
// Uses digits 0-9, then A-Z
// - 42 ÷ 36 = 1 remainder 6 → "6"
// - 1 ÷ 36 = 0 remainder 1 → "1"
// - Read backwards: "16"
// Result: "16"
✅ Supported Bases Reference
// ═══ All Supported Bases (2-36) ═══
// Base 2: Binary (digits: 0-1)
// Base 8: Octal (digits: 0-7)
// Base 10: Decimal (digits: 0-9)
// Base 16: Hexadecimal (digits: 0-9, A-F)
// Base 36: Alphanumeric (digits: 0-9, A-Z)
// Common examples:
int num = 255;
Integer.toString(num, 2) // "11111111" (binary)
Integer.toString(num, 8) // "377" (octal)
Integer.toString(num, 10) // "255" (decimal)
Integer.toString(num, 16) // "ff" (hex, lowercase)
Integer.toString(num, 36) // "73" (base 36)
// With uppercase for hex/base36:
Integer.toString(255, 16).toUpperCase() // "FF"
Integer.toString(100, 36).toUpperCase() // "2S"
// Error handling for invalid radix:
// Integer.toString(42, 1) // IllegalArgumentException (radix must be >= 2)
// Integer.toString(42, 37) // IllegalArgumentException (radix must be <= 36)
✅ Example Usage Scenarios
// ═══ Practical Use Cases ═══
// Scenario 1: Convert to common bases
int value = 1024;
System.out.println("Binary: " + convertToBaseUsingBuiltIn(value, 2)); // 10000000000
System.out.println("Octal: " + convertToBaseUsingBuiltIn(value, 8)); // 2000
System.out.println("Hex: " + convertToBaseUsingBuiltIn(value, 16)); // 400
// Scenario 2: Display memory sizes
int bytes = 1024;
System.out.println("1024 bytes in hex: " +
convertToBaseBuiltInUppercase(bytes, 16)); // "400"
// Scenario 3: Encode numbers as alphanumeric (base 36)
int id = 12345;
String encoded = convertToBaseBuiltInUppercase(id, 36); // "9IX"
System.out.println("ID encoded: " + encoded);
// Scenario 4: Create checksum or hash-like values
int checksum = 987654;
String base36 = convertToBaseBuiltInUppercase(checksum, 36); // "IIAK"
// Scenario 5: Loop through all supported bases
int num = 42;
System.out.println("42 in various bases:");
for(int base = 2; base <= 16; base++){
System.out.println(" Base " + base + ": " +
convertToBaseUsingBuiltIn(num, base));
}
// Output:
// Base 2: 101010
// Base 3: 1120
// Base 4: 222
// Base 5: 132
// Base 6: 110
// Base 7: 60
// Base 8: 52
// Base 9: 46
// Base 10: 42
// Base 11: 3a
// Base 12: 36
// Base 13: 32
// Base 14: 2e
// Base 15: 2c
// Base 16: 2a
// Scenario 6: Reverse conversion (from any base back to decimal)
// String binary = convertToBaseUsingBuiltIn(42, 2); // "101010"
// int back = Integer.parseInt("101010", 2); // 42 ✓
// (Note: parseInt is the reverse operation!)
✅ When to Use Built-In vs. Dibble-Dabble
// ✅ Use convertToBaseUsingBuiltIn() when:
// - Writing production code
// - You need any base 2-36
// - You want clean, readable code
// - Performance matters
// - You just need the result
// ✅ Use convertFromBaseTenToBaseB() when:
// - Learning base conversion for the first time
// - Studying algorithms (CS fundamentals, interview prep)
// - You need bases 2-9 only
// - Subscript notation (₂, ₈) is important
// - You want to understand HOW it works
// - Teaching others or doing AP exam review
// Real-world example:
// Your APCS-A project needs hex colors for a graphics program?
// → Use convertToBaseBuiltInUppercase(rgbValue, 16) // Clean one-liner
// Your algorithms course requires you to implement base conversion?
// → Use convertFromBaseTenToBaseB() // Shows understanding
// You're preparing for a coding interview and get asked about base conversion?
// → Know both! Explain the algorithm (dibble-dabble)
// → Then mention Integer.toString() as the practical solution
✅ Related Utilities
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)
// ═══ LCM Examples ═══
// Example 1: 12 and 18
// Multiples of 12: 12, 24, 36, 48, 60, ...
// Multiples of 18: 18, 36, 54, 72, 90, ...
// Common multiples: 36, 72, 108, ...
// LEAST common multiple: 36 ✓
calculateLCM(12, 18) // Returns 36
// Example 2: 4 and 6
// Multiples of 4: 4, 8, 12, 16, 20, ...
// Multiples of 6: 6, 12, 18, 24, 30, ...
// Common multiples: 12, 24, 36, ...
// LEAST common multiple: 12 ✓
calculateLCM(4, 6) // Returns 12
// Example 3: 7 and 11 (coprime - no common factors)
// Multiples of 7: 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, ...
// Multiples of 11: 11, 22, 33, 44, 55, 66, 77, 88, ...
// Common multiples: 77, 154, 231, ...
// LEAST common multiple: 77 ✓
// (For coprime numbers: LCM = a × b)
calculateLCM(7, 11) // Returns 77
✅ How It Works: The GCF-Based Formula
// ═══ The Mathematical Relationship ═══
// Important Formula: LCM(a, b) × GCF(a, b) = a × b
// Therefore: LCM(a, b) = (a × b) / GCF(a, b)
// Example: LCM(12, 18)
// Step 1: Calculate GCF(12, 18)
// GCF(12, 18) = 6
// Step 2: Apply formula
// LCM(12, 18) = (12 × 18) / 6 = 216 / 6 = 36 ✓
// Example: LCM(4, 6)
// Step 1: Calculate GCF(4, 6)
// GCF(4, 6) = 2
// Step 2: Apply formula
// LCM(4, 6) = (4 × 6) / 2 = 24 / 2 = 12 ✓
// Example: LCM(7, 11)
// Step 1: Calculate GCF(7, 11)
// GCF(7, 11) = 1 (coprime - no common factors)
// Step 2: Apply formula
// LCM(7, 11) = (7 × 11) / 1 = 77 / 1 = 77 ✓
// Why is GCF useful?
// - Direct calculation: Finding all multiples is slow for large numbers
// - GCF method: Fast using Euclidean algorithm (O(log n))
// - Formula avoids brute force!
✅ GCF and LCM: Partner Methods
// ═══ Using Both Methods Together ═══
int a = 12, b = 18;
// Find GCF (Greatest Common Factor / Divisor)
int gcf = calculateGCF(a, b); // 6
// GCF answers: "What's the largest number that divides both?"
// Answer: 6 divides both 12 and 18
// Find LCM (Least Common Multiple)
int lcm = calculateLCM(a, b); // 36
// LCM answers: "What's the smallest number divisible by both?"
// Answer: 36 is divisible by both 12 and 18
// Verify the relationship
boolean relationship = (gcf * lcm == a * b); // true
System.out.println(gcf + " × " + lcm + " = " + (gcf * lcm));
System.out.println(a + " × " + b + " = " + (a * b));
// Output:
// 6 × 36 = 216
// 12 × 18 = 216 ✓
// Real example: Common denominator
// Fractions: 7/12 + 5/18
// Find LCM(12, 18) = 36 (common denominator)
// Convert: 7/12 = 21/36, 5/18 = 10/36
// Add: 21/36 + 10/36 = 31/36 ✓
✅ Practical Applications
// ═══ Real-World Uses of LCM ═══
// 1. Finding Common Denominators (Fractions)
int denom1 = 12, denom2 = 18;
int commonDenom = calculateLCM(denom1, denom2); // 36
System.out.println("Common denominator: " + commonDenom);
// 2. Synchronizing Events (Scheduling Problem)
// Bus A arrives every 12 minutes, Bus B every 18 minutes
// When do they arrive at the same time?
int lcm = calculateLCM(12, 18); // 36 minutes
System.out.println("Buses meet every " + lcm + " minutes");
// Answer: Both buses arrive together every 36 minutes
// 3. Creating Repeating Patterns
// Pattern 1 repeats every 4 steps, Pattern 2 every 6 steps
// When do both patterns repeat together?
int lcm = calculateLCM(4, 6); // 12
System.out.println("Patterns align every " + lcm + " steps");
// 4. Computing Gear Ratios (Mechanics)
// Gear A has 12 teeth, Gear B has 18 teeth
// After how many rotations are they in the same position?
int alignmentRotations = calculateLCM(12, 18) / 12; // 3 rotations of Gear A
System.out.println("Gears align after " + alignmentRotations + " rotations");
// 5. Array Indexing / Game Development
// Particle 1 updates every 12 frames, Particle 2 every 18 frames
// When do both update at the same frame?
int syncFrame = calculateLCM(12, 18); // Frame 36
System.out.println("Both particles update at frame " + syncFrame);
✅ Why This Method Composability Matters
All 29 utilities plus two support classes — ready to use in your projects.
TNTMath.java, logically organized and searchableTNTPower class (separate file): Represents base^exponent (bx)TNTRadical class (separate file): Represents simplified radicals (c·√r)
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.
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².
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.
TNTMath.java and you're done—it's self-containedTNTPower.java to get elegant Unicode superscriptsTNTRadical.java for automatic simplificationTNTMath.calculateGCF() directly; if separate, add import statements