﻿/**
 * TNTMath.java
 * 
 * A comprehensive collection of battle-tested mathematical utility methods
 * designed for APCS-A education and practical programming.
 * 
 * This class contains 25+ static utility methods covering:
 * - Basic mathematical operations (GCF, rounding, mean, median)
 * - Number properties (digit counting, even/odd detection, factorial)
 * - Base conversion (multiple approaches: educational, specialized, built-in)
 * - Number theory (prime checking, prime factorization, logarithms)
 * - Random number generation (integers and doubles)
 * - Radical simplification (c·√r format with Unicode superscripts)
 * - Power representation (base^exponent with Unicode formatting)
 * 
 * Methods are organized alphabetically by name for easy reference.
 * 
 * Supporting Classes:
 * - TNTPower: Represents base and exponent (a^n) for educational purposes
 * - TNTRadical: Represents radicals in simplified form (c·√r)
 * 
 * Version: 2.0
 * Last Updated: 2025
 * 
 * Usage:
 *   // Static methods called directly on the class
 *   int gcf = TNTMath.calculateGCF(48, 18);
 *   double mean = TNTMath.calculateMean(numbers);
 *   boolean prime = TNTMath.isPrime(17);
 *   
 *   // Using supporting classes
 *   TNTPower power = new TNTPower(2, 5);        // 2^5
 *   TNTRadical rad = new TNTRadical(2, 300);    // 2·√300
 * 
 * @author TNT (Teacher and Tutor) Team
 */

import java.util.ArrayList;
import java.util.Random;
import java.util.Collections;
import java.util.HashMap;
import java.text.DecimalFormat;

public class TNTMath {

    /**
     * Calculates the Greatest Common Factor (GCF) of two integers
     * Uses the Euclidean algorithm: GCF(a, b) = GCF(b, a mod b)
     * @param n1 first integer (can be negative; absolute value is used)
     * @param n2 second integer (can be negative; absolute value is used)
     * @return int the greatest common factor of n1 and n2
     *
     * Example: calculateGCF(60, 48) returns 12
     *          calculateGCF(17, 19) returns 1 (coprime primes)
     *          calculateGCF(100, 50) returns 50
     */
    public static int calculateGCF(int n1, int n2){
        int rem = 0;
        int gcf = 0;
        do{
            rem = Math.abs(n1) % Math.abs(n2);
            if (rem == 0)
                gcf = n2;
            else{
                n1 = n2;
                n2 = rem;
            }
        }
        while (rem != 0);
        return gcf;
    }//end calculateGCF(int, int)

    /**
     * Calculates the Greatest Common Factor (GCF) of two long integers
     * Uses the Euclidean algorithm: GCF(a, b) = GCF(b, a mod b)
     * This overload supports larger numbers than int
     * @param n1 first long integer (can be negative; absolute value is used)
     * @param n2 second long integer (can be negative; absolute value is used)
     * @return long the greatest common factor of n1 and n2
     *
     * Example: calculateGCF(60L, 48L) returns 12L
     *          calculateGCF(1000000L, 500000L) returns 500000L
     */
    public static long calculateGCF(long n1, long n2){
        long rem = 0;
        long gcf = 0;
        do{
            rem = Math.abs(n1) % Math.abs(n2);
            if (rem == 0)
                gcf = n2;
            else{
                n1 = n2;
                n2 = rem;
            }
        }
        while (rem != 0);
        return gcf;
    }//end calculateGCF(long, long)

    /**
     * Calculates the Least Common Multiple (LCM) of two integers.
     * Uses the formula: LCM(a,b) = (a * b) / GCF(a,b)
     * 
     * @param a first integer
     * @param b second integer
     * @return the LCM of a and b
     * 
     * @example calculateLCM(12, 18) returns 36
     */
    public static int calculateLCM(int a, int b) {
        return (a * b) / calculateGCF(a, b);
    } // end calculateLCM

    /**
     * Calculates the arithmetic mean (average) of a list of integers
     * @param aL the ArrayList of integers
     * @return the mean as a double
     *
     * Example: calculateMean([1, 2, 3, 4, 5]) returns 3.0
     *          calculateMean([10, 20, 30]) returns 20.0
     */
    public static double calculateMean(ArrayList<Integer> aL){
        if(aL == null || aL.size() == 0) return 0.0;

        int sum = 0;
        for(int value : aL){
            sum += value;
        }
        return (double) sum / aL.size();
    }//end calculateMean

    /**
     * Calculates the median of a list of integers
     * ⚠️ IMPORTANT: This method sorts the ArrayList! Do not use if you need the original order.
     * @param aL the ArrayList of integers (will be sorted by this method)
     * @return the median as a double
     *
     * Example: calculateMedian([3, 1, 4, 1, 5]) → sorts to [1, 1, 3, 4, 5] → returns 3.0
     *          calculateMedian([2, 1, 3, 4]) → sorts to [1, 2, 3, 4] → returns 2.5 (average of middle two)
     */
    public static double calculateMedian(ArrayList<Integer> aL){
        if(aL == null || aL.size() == 0) return 0.0;

        Collections.sort(aL);
        int n = aL.size();

        if(n % 2 == 1){
            return (double) aL.get(n / 2);
        }
        else{
            int mid1 = aL.get(n / 2 - 1);
            int mid2 = aL.get(n / 2);
            return (double) (mid1 + mid2) / 2.0;
        }
    }//end calculateMedian

    /**
     * Calculates the median of a list of integers with option to preserve original
     * @param aL the ArrayList of integers
     * @param shouldPreserveOriginal boolean to allow/disallow preservation of original aL
     * @return the median as a double
     */
    public static double calculateMedian(ArrayList<Integer> aL, boolean shouldPreserveOriginal){
        if(aL == null || aL.size() == 0) return 0.0;

        ArrayList<Integer> data;
        if(shouldPreserveOriginal){
            ArrayList<Integer> aCopy = new ArrayList<Integer>(aL);
            data = aCopy;
        }else{
            data = aL;
        }

        Collections.sort(data);
        int n = data.size();

        if(n % 2 == 1){
            return (double) data.get(n / 2);
        }
        else{
            int mid1 = data.get(n / 2 - 1);
            int mid2 = data.get(n / 2);
            return (double) (mid1 + mid2) / 2.0;
        }
    }//end calculateMedian(ArrayList, boolean)

    /**
     * Counts the number of digits in an integer using arithmetic (no string conversion)
     * Handles negative numbers by using Math.abs() (the minus sign is not counted)
     * Special case: 0 has 1 digit
     * @param n the integer to count digits of
     * @return int the number of digits
     *
     * Example: countDigits(42) returns 2
     *          countDigits(-12345) returns 5 (minus sign ignored)
     *          countDigits(0) returns 1
     */
    public static int countDigits(int n){
        if(n == 0) return 1;
        n = Math.abs(n);
        int count = 0;
        while(n > 0){
            count++;
            n /= 10;
        }
        return count;
    }//end countDigits(int)

    /**
     * Counts the number of digits in a long integer using arithmetic (no string conversion)
     * Handles negative numbers by using Math.abs() (the minus sign is not counted)
     * Special case: 0 has 1 digit
     * @param n the long integer to count digits of
     * @return int the number of digits
     *
     * Example: countDigits(9876543210L) returns 10
     *          countDigits(-555L) returns 3
     *          countDigits(0L) returns 1
     */
    public static int countDigits(long n){
        if(n == 0) return 1;
        n = Math.abs(n);
        int count = 0;
        while(n > 0){
            count++;
            n /= 10;
        }
        return count;
    }//end countDigits(long)

    /**
     * Counts the number of UNIQUE digits in an integer using a Set
     * Handles negative numbers by using Math.abs() (the minus sign is ignored)
     * Example: 1223334 has digits [1,2,2,3,3,3,4] but only 4 unique: {1,2,3,4}
     * @param n the integer to count unique digits of
     * @return int the number of unique digits
     *
     * Example: countUniqueDigits(42) returns 2 (digits 4,2 both unique)
     *          countUniqueDigits(1223334) returns 4 (unique digits: 1,2,3,4)
     *          countUniqueDigits(-555) returns 1 (only digit 5)
     */
    public static int countUniqueDigits(int n){
        n = Math.abs(n);
        java.util.Set<Integer> uniqueDigits = new java.util.HashSet<Integer>();
        while(n > 0){
            uniqueDigits.add(n % 10);
            n /= 10;
        }
        return uniqueDigits.size();
    }//end countUniqueDigits(int)

    /**
     * Counts the number of UNIQUE digits in a long integer using a Set
     * Handles negative numbers by using Math.abs() (the minus sign is ignored)
     * Example: 1223334 has digits [1,2,2,3,3,3,4] but only 4 unique: {1,2,3,4}
     * @param n the long integer to count unique digits of
     * @return int the number of unique digits
     *
     * Example: countUniqueDigits(9876543210L) returns 10 (all digits unique)
     *          countUniqueDigits(111222333L) returns 3 (unique digits: 1,2,3)
     *          countUniqueDigits(-77777L) returns 1 (only digit 7)
     */
    public static int countUniqueDigits(long n){
        n = Math.abs(n);
        java.util.Set<Integer> uniqueDigits = new java.util.HashSet<Integer>();
        while(n > 0){
            uniqueDigits.add((int)(n % 10));
            n /= 10;
        }
        return uniqueDigits.size();
    }//end countUniqueDigits(long)

    /**
     * Converts an integer from base 10 (decimal) to any base 2-9 using the dibble-dabble algorithm
     * Uses repeated division and remainder extraction
     * Bases outside 2-9 return the base-10 form as error handling
     * @param x the integer to convert
     * @param n the target base (2-9)
     * @return String formatted as "(result)₍base₎"
     *
     * Example: convertFromBaseTenToBaseB(42, 2) returns "(101010)₂"
     *          convertFromBaseTenToBaseB(42, 8) returns "(52)₈"
     */
    public static String convertFromBaseTenToBaseB(int x, int n) {
        if(2 > n || n > 9){
            return "(" + x + ")₁₀";
        }
        
        String temp = "";
        int q, r;
        do{
            q = x / n;
            r = x % n;
            x = q;
            temp = String.valueOf(r) + temp;
        } while(q > 0);
        
        String[] subscripts = {"", "₁", "₂", "₃", "₄", "₅", "₆", "₇", "₈", "₉"};
        return "(" + temp + ")" + subscripts[n];
    }//end convertFromBaseTenToBaseB

    /**
     * Converts an integer from base 10 (decimal) to hexadecimal (base 16) using Java's built-in method
     * Uses Integer.toHexString() for the conversion, then formats with uppercase letters and subscript
     * @param x the integer to convert
     * @return String formatted as "(result)₁₆" with uppercase hex digits
     *
     * Example: convertFromBaseTenToHex(255) returns "(FF)₁₆"
     *          convertFromBaseTenToHex(128) returns "(80)₁₆"
     *          convertFromBaseTenToHex(0) returns "(0)₁₆"
     */
    public static String convertFromBaseTenToHex(int x) {
        String hex = Integer.toHexString(x).toUpperCase();
        return "(" + hex + ")₁₆";
    }//end convertFromBaseTenToHex

    /**
     * Converts an integer from base 10 (decimal) to any base 2-36 using Java's built-in Integer.toString()
     * This is the simplest and most practical approach for most applications
     * Supports all bases from 2-36 (0-9, then A-Z for digits 10-35)
     * @param number the integer to convert
     * @param radix the target base (2-36)
     * @return String formatted as the number in the given radix
     *
     * Example: convertToBaseUsingBuiltIn(42, 2) returns "101010"
     *          convertToBaseUsingBuiltIn(255, 16) returns "ff"
     *          convertToBaseUsingBuiltIn(42, 36) returns "16"
     */
    public static String convertToBaseUsingBuiltIn(int number, int radix) {
        if(radix < 2 || radix > 36){
            return "Invalid radix (must be 2-36)";
        }
        return Integer.toString(number, radix);
    }//end convertToBaseUsingBuiltIn

    /**
     * Converts an integer from base 10 (decimal) to any base 2-36, with uppercase letters
     * Uses Java's built-in Integer.toString() and converts to uppercase for hex/octal display
     * @param number the integer to convert
     * @param radix the target base (2-36)
     * @return String formatted in UPPERCASE for bases > 10
     *
     * Example: convertToBaseBuiltInUppercase(255, 16) returns "FF"
     *          convertToBaseBuiltInUppercase(100, 36) returns "2S"
     */
    public static String convertToBaseBuiltInUppercase(int number, int radix) {
        if(radix < 2 || radix > 36){
            return "Invalid radix (must be 2-36)";
        }
        return Integer.toString(number, radix).toUpperCase();
    }//end convertToBaseBuiltInUppercase


    /**
     * Extracts the fractional (decimal) part of a double value
     * Uses Math.floor() arithmetic method instead of string manipulation
     * Formula: fractionalPart(x) = x - Math.floor(x)
     * Preserves sign of original number for negative values
     * @param x the double value to extract fractional part from
     * @return double the fractional part (always >= 0 for positive x; sign preserved for negative x)
     *
     * Example: getFractionalPart(5.75) returns 0.75
     *          getFractionalPart(-3.42) returns 0.58 (Note: floor(-3.42) = -4, so -3.42 - (-4) = 0.58)
     *          getFractionalPart(10.0) returns 0.0
     */
    public static double getFractionalPart(double x){
        return x - Math.floor(x);
    }//end getFractionalPart

    /**
     * Finds the largest factor of n that is less than or equal to sqrt(n)
     * Used to create nearly square matrices with balanced dimensions
     * @param n the number to find the balanced factor of (positive integer)
     * @return int the largest factor <= sqrt(n)
     *
     * Example: findFactorClosestToSquareRoot(60) returns 6 (factors: 6 × 10)
     *          findFactorClosestToSquareRoot(100) returns 10 (perfect square: 10 × 10)
     *          findFactorClosestToSquareRoot(48) returns 6 (factors: 6 × 8)
     */
    public static int findFactorClosestToSquareRoot(int n){
        double sroot = Math.sqrt(n);
        int candidate = 1;
        for(int i = 1; i <= sroot; i++){
            if(n % i == 0){
                int newFactor = i;
                if(newFactor > candidate) candidate = newFactor;
            }
        }
        return candidate;
    }//end findFactorClosestToSquareRoot

    /**
     * Finds the first (smallest) perfect square larger than x
     * Uses Math.ceil(sqrt(x)) then squares it
     * @param x the value to find the next perfect square for (long)
     * @return double the first perfect square strictly greater than x
     *
     * Example: findFirstPerfectSquareLargerThan(24) returns 25.0 (5²)
     *          findFirstPerfectSquareLargerThan(100) returns 121.0 (11²)
     *          findFirstPerfectSquareLargerThan(1000) returns 1024.0 (32²)
     */
    public static double findFirstPerfectSquareLargerThan(long x){
        double root = Math.sqrt(x);
        double upperBoundRoot = Math.ceil(root);
        double ps = Math.pow(upperBoundRoot, 2);
        return ps;
    }//end findFirstPerfectSquareLargerThan

    /**
     * Finds all prime factors of n, including 1 for n=1, in sorted ascending order
     * Uses trial division with pre-computed prime list for efficiency
     * @param n the number to factor (must be positive)
     * @return ArrayList<Integer> of all prime factors (includes duplicates), sorted ascending
     *
     * Example: findPrimeFactorsOf(60) returns [2, 2, 3, 5]
     *          findPrimeFactorsOf(100) returns [2, 2, 5, 5]
     *          findPrimeFactorsOf(1) returns [1]
     */
    public static ArrayList<Integer> findPrimeFactorsOf(long n){
        ArrayList<Integer> factors = new ArrayList<Integer>();

        if(n == 1) {
            factors.add(1);
            return factors;
        }

        int[] primes = {2,3,5,7,11,13,17,19,23,29,
            31,37,41,43,47,53,59,61,67,71,
            73,79,83,89,97,101,103,107,109,113,
            127,131,137,139,149,151,157,163,167,173,
            179,181,191,193,197,199,211,223,227,229,
            233,239,241,251,257,263,269,271,277,281,
            283,293,307,311,313,317,331,337,347,349,
            353,359,367,373,379,383,389,397,401,409,
            419,421,431,433,439,443,449,457,461,463,
            467,479,487,491,499,503,509,521,523,541,
            547,557,563,569,571,577,587,593,599,601,
            607,613,617,619,631,641,643,647,653,659,
            661,673,677,683,691,701,709,719,727,733,
            739,743,751,757,761,769,773,787,797,809,
            811,821,823,827,829,839,853,857,859,863,
            877,881,883,887,907,911,919,929,937,941,
            947,953,967,971,977,983,991,997,1009,1013,
            1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,
            1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,
            1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,
            1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,
            1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,
            1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,
            1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,
            1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,
            1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,
            1663,1667,1669,1693,1697,1699,1709,1721,1723,1733,
            1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,
            1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,
            1901,1907,1913,1931,1933,1949,1951,1973,1979,1987,
            1993,1997,1999
        };

        for(int prime : primes){
            if(prime > n) break;
            while(n % prime == 0){
                factors.add(prime);
                n /= prime;
            }
        }

        if(n > 1){
            for(long i = 2003; i * i <= n; i += 2){
                while(n % i == 0){
                    factors.add((int)i);
                    n /= i;
                }
            }
            if(n > 1){
                factors.add((int)n);
            }
        }

        return factors;
    }//end findPrimeFactorsOf

    /**
     * Finds prime factors and consolidates them as TNTPower objects
     * Example: 60 = 2×2×3×5 becomes [2², 3, 5] with Unicode superscripts
     * @param n the number to factor
     * @return ArrayList<TNTPower> of consolidated prime factors (with elegant Unicode or caret notation)
     *
     * Example: findConsolidatedPrimeFactorsOf(60) returns TNTPower objects: 2², 3, 5
     *          findConsolidatedPrimeFactorsOf(1000) returns: 2³, 5³
     */
    public static ArrayList<TNTPower> findConsolidatedPrimeFactorsOf(long n){
        ArrayList<TNTPower> consolidatedFactors = new ArrayList<TNTPower>();

        ArrayList<Integer> allFactors = findPrimeFactorsOf(n);

        if(allFactors.isEmpty()) return consolidatedFactors;

        int currentFactor = allFactors.get(0);
        int count = 1;

        for(int i = 1; i < allFactors.size(); i++){
            int factor = allFactors.get(i);
            if(factor == currentFactor){
                count++;
            } else {
                consolidatedFactors.add(new TNTPower(currentFactor, count));
                currentFactor = factor;
                count = 1;
            }
        }

        consolidatedFactors.add(new TNTPower(currentFactor, count));

        return consolidatedFactors;
    }//end findConsolidatedPrimeFactorsOf

    /**
     * Finds the minimum, maximum, and range of integers in an ArrayList
     * Uses Collections.min() and Collections.max() for efficiency
     * @param aL the ArrayList of integers to analyze
     * @param shouldPreserveOriginal boolean to preserve the original list (creates a copy if true)
     * @return an integer array [min, max, range] where range = max - min
     *
     * Example: findExtrema([3, 1, 4, 1, 5], false) returns [1, 5, 4]
     *          findExtrema([10, 20, 15], true) returns [10, 20, 10] and original list unchanged
     */
    public static int[] findExtrema(ArrayList<Integer> aL, boolean shouldPreserveOriginal){
        if(aL == null || aL.size() == 0) return new int[]{0, 0, 0};

        ArrayList<Integer> data = aL;
        if(shouldPreserveOriginal){
            data = new ArrayList<Integer>(aL);
        }

        int min = Collections.min(data);
        int max = Collections.max(data);
        int range = max - min;

        return new int[]{min, max, range};
    }//end findExtrema

    /**
     * Finds the mode(s) of integers in an ArrayList
     * Mode is the value(s) that appear most frequently
     * @param aL the ArrayList of integers to analyze
     * @return ArrayList of integers representing all modes (handles ties); empty if no mode exists
     *
     * Example: findMode([1, 2, 2, 3, 3, 3]) returns [3] (3 appears 3 times)
     *          findMode([1, 1, 2, 2, 3]) returns [1, 2] (both appear 2 times—a tie!)
     *          findMode([1, 2, 3, 4]) returns [] (no mode—all equally frequent)
     */
    public static ArrayList<Integer> findMode(ArrayList<Integer> aL){
        if(aL == null || aL.size() == 0) return new ArrayList<Integer>();

        HashMap<Integer, Integer> frequency = new HashMap<Integer, Integer>();
        for(Integer num : aL){
            frequency.put(num, frequency.getOrDefault(num, 0) + 1);
        }

        int maxFrequency = 0;
        for(Integer count : frequency.values()){
            if(count > maxFrequency){
                maxFrequency = count;
            }
        }

        ArrayList<Integer> modes = new ArrayList<Integer>();
        for(Integer num : frequency.keySet()){
            if(frequency.get(num) == maxFrequency){
                modes.add(num);
            }
        }

        return modes;
    }//end findMode

    /**
     * Finds the mode(s) and displays all values with their frequencies
     * @param aL the ArrayList of integers to analyze
     * @return a HashMap where key=value, value=frequency count
     *
     * Example: findModeWithFrequency([1, 2, 2, 3, 3, 3])
     *          Returns: {1=1, 2=2, 3=3}
     *          Use this to see ALL frequency counts, not just the modes
     */
    public static HashMap<Integer, Integer> findModeWithFrequency(ArrayList<Integer> aL){
        HashMap<Integer, Integer> frequency = new HashMap<Integer, Integer>();

        if(aL == null || aL.size() == 0) return frequency;

        for(Integer num : aL){
            frequency.put(num, frequency.getOrDefault(num, 0) + 1);
        }

        return frequency;
    }//end findModeWithFrequency

    /**
     * Generates an ArrayList of n random integers in a closed interval
     * @param rng the Random object (can be seeded for repeatability)
     * @param min the minimum value (inclusive)
     * @param max the maximum value (inclusive)
     * @param n the number of random integers to generate
     * @return an ArrayList containing n random integers between min and max (inclusive)
     *
     * Example: Random rng = new Random(42);
     *          generateRandomIntegersIn(rng, 1, 10, 5) returns [7, 3, 8, 2, 9]
     */
    public static ArrayList<Integer> generateRandomIntegersIn(Random rng, int min, int max, int n){
        ArrayList<Integer> result = new ArrayList<Integer>();
        for(int i = 0; i < n; i++){
            result.add(getRandom(rng, min, max));
        }
        return result;
    }//end generateRandomIntegersIn

    /**
     * Calculates the remainder when dividing a long by an int using mathematical definition
     * Uses: remainder = numerator - (quotient × denominator)
     * This method is needed when modulus operator (%) is insufficient or inapplicable
     * @param num the numerator (long)
     * @param denom the denominator (int)
     * @return int the remainder
     *
     * Example: getRemainder(42L, 5) returns 2 (same as 42 % 5)
     *          getRemainder(1000000000L, 7) works reliably with large numbers
     *
     * Historical note: Used in ConvertToHex4GUI.java for base conversion algorithms
     */
    public static int getRemainder(long num, int denom){
        long q = num / denom;
        int remainder = (int)(num - q * denom);
        return remainder;
    }//end getRemainder(long, int)

    /**
     * Calculates the remainder when dividing a long by a double using mathematical definition
     * Uses: remainder = numerator - (quotient × denominator)
     * This is essential because the modulus operator (%) does NOT work with floating-point types
     * @param num the numerator (long)
     * @param denom the denominator (double)
     * @return long the remainder
     *
     * Example: getRemainder(42L, 5.0) returns 2 (42 - 8*5 = 2)
     *          getRemainder(100L, 3.33) works with decimal divisors
     *
     * Historical note: Used in ConvertToHexGUI.java (April 2003) for flexible base conversion
     */
    public static long getRemainder(long num, double denom){
        long r;
        double q = (double) num / denom;
        r = (long)(num - (long)q * denom);
        return r;
    }//end getRemainder(long, double)

    /**
     * Generates a random integer in a closed interval using the Random class
     * @param rng the Random object (can be seeded for repeatability)
     * @param min the minimum value (inclusive)
     * @param max the maximum value (inclusive)
     * @return a random integer between min and max (inclusive)
     *
     * Example: Random rng = new Random(42);
     *          getRandom(rng, 1, 10) returns a random int between 1 and 10
     */
    public static int getRandom(Random rng, int min, int max){
        max = Math.max(min, max);
        min = Math.min(min, max);
        int range = max - min;
        int x = min + rng.nextInt(range + 1);
        return x;
    }//end getRandom(Random, int, int)

    /**
     * Generates a random double in a closed interval using the Random class
     * @param rng the Random object (can be seeded for repeatability)
     * @param min the minimum value (inclusive)
     * @param max the maximum value (inclusive)
     * @return a random double between min and max (inclusive)
     *
     * Example: Random rng = new Random(42);
     *          getRandom(rng, 0.0, 1.0) returns a random double between 0.0 and 1.0
     */
    public static double getRandom(Random rng, double min, double max){
        max = Math.max(min, max);
        min = Math.min(min, max);
        double range = max - min;
        double adjustedRange = range + Math.ulp(range);
        double x = min + adjustedRange * rng.nextDouble();
        return x;
    }//end getRandom(Random, double, double)

    /**
     * Generates a random integer in a closed interval using Math.random()
     * @param min the minimum value (inclusive)
     * @param max the maximum value (inclusive)
     * @return a random integer between min and max (inclusive)
     *
     * Example: getRandom(1, 10) returns a random int between 1 and 10
     */
    public static int getRandom(int min, int max){
        max = Math.max(min, max);
        min = Math.min(min, max);
        int range = max - min;
        int x = min + (int) ((range + 1) * Math.random());
        return x;
    }//end getRandom(int, int)

    /**
     * Generates a random double in a closed interval using Math.random()
     * @param min the minimum value (inclusive)
     * @param max the maximum value (inclusive)
     * @return a random double between min and max (inclusive)
     *
     * Example: getRandom(0.0, 1.0) returns a random double between 0.0 and 1.0
     */
    public static double getRandom(double min, double max){
        max = Math.max(min, max);
        min = Math.min(min, max);
        double range = max - min;
        double adjustedRange = range + Math.ulp(range);
        double x = min + adjustedRange * Math.random();
        return x;
    }//end getRandom(double, double)

    /**
     * Tests whether an integer is even (divisible by 2)
     * Uses modulo operator: even numbers have remainder 0 when divided by 2
     * Simplified form: directly returns the boolean result
     * @param n the integer to test
     * @return true if n is even, false if n is odd
     *
     * Example: isEven(42) returns true
     *          isEven(43) returns false
     *          isEven(-8) returns true (negative evens work too)
     */
    public static boolean isEven(int n){
        return n % 2 == 0;
    }//end isEven(int)

    /**
     * Tests whether a long integer is even (divisible by 2)
     * Uses modulo operator: even numbers have remainder 0 when divided by 2
     * Simplified form: directly returns the boolean result
     * @param n the long integer to test
     * @return true if n is even, false if n is odd
     *
     * Example: isEven(9876543210L) returns true
     *          isEven(999999999L) returns false
     *          isEven(-555555L) returns false
     */
    public static boolean isEven(long n){
        return n % 2 == 0;
    }//end isEven(long)

    /**
     * Determines if a number is prime
     * @param checkNumber the number to check for primality
     * @return true if the number is prime, false otherwise
     * Example: isPrime(17) returns true
     *          isPrime(12) returns false
     */
    public static boolean isPrime(long checkNumber){
        if(checkNumber == 1) return false;
        if(checkNumber == 2) return true;
        else if(checkNumber % 2 == 0) return false;
        double root = Math.sqrt(checkNumber);
        double uBound = Math.ceil(root);
        for (long i = 3; i <= uBound; i+=2){
            if (checkNumber % i == 0) return false;
        }
        return true;
    }//end isPrime

    /**
     * Calculates logarithm base 10 using Change of Base formula: log₁₀(x) = log(x) / log(10)
     * @param x the value to take log base 10 of (must be positive)
     * @return double log base 10 of x
     *
     * Example: logBase10(100) returns 2.0 (since 10² = 100)
     *          logBase10(1000) returns 3.0 (since 10³ = 1000)
     */
    public static double logBase10(double x){
        return Math.log(x) / Math.log(10);
    }//end logBase10

    /**
     * Calculates logarithm of any base using Change of Base formula: log_b(x) = log(x) / log(b)
     * @param x the value to take logarithm of (must be positive)
     * @param b the base of the logarithm (must be positive and not equal to 1)
     * @return double logarithm base b of x
     *
     * Example: logBaseB(8, 2) returns 3.0 (since 2³ = 8)
     *          logBaseB(27, 3) returns 3.0 (since 3³ = 27)
     *          logBaseB(16, 4) returns 2.0 (since 4² = 16)
     */
    public static double logBaseB(double x, double b){
        return Math.log(x) / Math.log(b);
    }//end logBaseB

    /**
     * Calculates n! (n factorial) = n × (n-1) × (n-2) × ... × 1
     * Uses long to handle larger values; safe up to 20! before overflow
     * Base cases: 0! = 1 and 1! = 1
     * @param n the number to calculate factorial of (should be 0 to 20 for safe results)
     * @return long n factorial; Long.MAX_VALUE if overflow would occur
     *
     * Example: longFactorial(5) returns 120
     *          longFactorial(0) returns 1
     *          longFactorial(10) returns 3628800
     *          longFactorial(20) returns 2432902008176640000
     */
    public static long longFactorial(int n){
        if(n < 0) return 0;
        if(n == 0 || n == 1) return 1;
        long product = 1;
        for(int i = 2; i <= n; i++){
            if(product > Long.MAX_VALUE / i) return Long.MAX_VALUE;
            product *= i;
        }
        return product;
    }//end longFactorial

    /**
     * Rounds a double to n decimal places
     * @param x the number to round
     * @param n the number of decimal places (positive rounds right, negative rounds left)
     * @return the rounded value
     * Example: roundToNearest(3.14159, 2) returns 3.14
     *          roundToNearest(1234.5, -2) returns 1200
     */
    public static double roundToNearest(double x, int n) {
        double roundedValue = x;
        double powTen = Math.pow(10, n);
        roundedValue = Math.round(roundedValue * powTen);
        roundedValue /= powTen;
        return roundedValue;
    }//end roundToNearest

    /**
     * Safely compares two floating-point numbers using a tolerance
     * @param x the first number
     * @param y the second number
     * @param tol the tolerance (epsilon) for comparison
     * @return true if |x-y| < tol, false otherwise
     *
     * Why not use ==?
     * Example: 0.1 + 0.2 == 0.3 returns FALSE (surprise!)
     * Due to binary floating-point representation, arithmetic produces tiny errors.
     * This method solves that problem using epsilon comparison.
     *
     * Example: areAboutEqual(0.1 + 0.2, 0.3, 0.0001) returns true
     */
    public static boolean areAboutEqual(double x, double y, double tol){
        tol = Math.abs(tol);
        if(tol == 0) tol = Double.MIN_NORMAL;
        return Math.abs(x - y) < tol;
    }//end areAboutEqual

}//end class TNTMath
