import java.text.DecimalFormat;

/**
 * TNTPower.java
 * 
 * Represents a base raised to an exponent (aⁿ)
 * Encapsulates the mathematical concept of powers with elegant Unicode formatting
 * 
 * Key Features:
 * - Stores base and exponent separately
 * - Calculates and caches the numeric value (Math.pow)
 * - Provides elegant toString() with Unicode superscripts for small exponents
 * - Uses caret notation (^) for large exponents (10+) for clarity
 * - Includes getters for base, exponent, and computed value
 * 
 * Unicode Superscripts:
 * - Exponent 0-9: Uses Unicode superscript characters (⁰, ¹, ², ³, ⁴, ⁵, ⁶, ⁷, ⁸, ⁹)
 * - Exponent 10+: Uses traditional caret notation (2^15) for readability
 * - Exponent 1: Omitted by convention (write 2, not 2¹)
 * 
 * Example Usage:
 *   TNTPower p1 = new TNTPower(2, 3);           // 2³ = 8
 *   TNTPower p2 = new TNTPower(10, 2);          // 10² = 100
 *   TNTPower p3 = new TNTPower(2, 15);          // 2^15 (uses caret for large exponents)
 *   System.out.println(p1.toString());          // Output: 2³
 *   System.out.println(p1.getValue());          // Output: 8.0
 * 
 * Use Cases:
 * - Factorization display: Represent prime powers elegantly (2² × 3 × 5)
 * - Scientific notation: Express large/small numbers as powers of 10
 * - Data structures: Store TNTPower objects in ArrayLists for factorization results
 * - Educational: Teach exponent notation and power calculations
 * 
 * @author TNT (Teacher and Tutor) Team
 * @version 1.0
 */
public class TNTPower {
    private long base;
    private long exponent;
    private double value;
    private DecimalFormat df = new DecimalFormat("###,###");

    /**
     * Default constructor
     * Creates TNTPower(1, 0) = 1⁰ = 1
     */
    public TNTPower(){
        base = 1;
        exponent = 0;
        value = Math.pow(base, exponent);
    }//end TNTPower()

    /**
     * Constructor with long base and exponent
     * @param b the base (long)
     * @param x the exponent (long)
     */
    public TNTPower(long b, long x){
        base = b;
        exponent = x;
        value = Math.pow(b, x);
    }//end TNTPower(long, long)

    /**
     * Constructor with int base and exponent
     * @param b the base (int)
     * @param x the exponent (int)
     */
    public TNTPower(int b, int x){
        base = b;
        exponent = x;
        value = Math.pow(b, x);
    }//end TNTPower(int, int)

    /**
     * Returns string representation with elegant Unicode superscripts for small exponents
     * or caret notation for large exponents
     * @return String representation: base with superscript exponent (e.g., "2³", "2^15")
     */
    public String toString(){
        // Unicode superscript array: ⁰ through ⁹
        String[] superscripts = {"⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"};

        // Case 1: Exponent is single-digit (0-9)
        // Use elegant Unicode superscripts
        if(exponent >= 0 && exponent <= 9) {
            if(exponent == 1) {
                // Convention: don't show exponent of 1 (just show the base)
                return df.format(base);
            } else {
                // Use Unicode superscript character
                return df.format(base) + superscripts[(int)exponent];
            }
        }
        // Case 2: Exponent is double-digit or larger (10+)
        // Use traditional caret notation for clarity
        else if(exponent > 9) {
            return df.format(base) + "^" + exponent;
        }
        // Case 3: Default fallback
        else {
            return df.format(base);
        }
    }//end toString

    /**
     * Gets the exponent
     * @return long the exponent
     */
    public long getExponent(){
        return exponent;
    }//end getExponent

    /**
     * Gets the base
     * @return long the base
     */
    public long getBase() {
        return base;
    }//end getBase

    /**
     * Gets the computed value (base ^ exponent)
     * @return double the value of base^exponent
     */
    public double getValue(){
        return value;
    }//end getValue

    /**
     * Finds the largest base b such that n = b^x for some exponent x >= 2
     * Returns the TNTPower representation with the largest possible base.
     * 
     * @param n the number to decompose as a perfect power
     * @return TNTPower object representing the largest base decomposition,
     *         or null if n cannot be expressed as b^x (b > 1, x >= 2)
     * 
     * @example findPowerDecomposition(64) returns TNTPower(8, 2) [since 8^2 = 64, largest b]
     * @example findPowerDecomposition(27) returns TNTPower(3, 3) [since 3^3 = 27]
     * @example findPowerDecomposition(32) returns TNTPower(2, 5) [since 2^5 = 32]
     * @example findPowerDecomposition(17) returns null [17 is prime, can't be perfect power]
     * @example findPowerDecomposition(1) returns TNTPower(1, 2) [1 = 1^2]
     * @example findPowerDecomposition(0) returns null [invalid input]
     * @example findPowerDecomposition(-8) returns null [negative input]
     * 
     * @note Algorithm:
     *       1. Handle edge cases (n <= 0 returns null; n = 1 returns 1^2)
     *       2. Compute maximum exponent as ceiling of log₂(n)
     *       3. For each exponent x from 2 to maxExponent:
     *          - Compute x-th root using Math.pow(n, 1.0/x)
     *          - Check if floor, exact, or ceiling value satisfies b^x = n
     *          - Return on first success (guarantees largest b)
     *       4. If no power found, return null
     * 
     * @note Floating-point precision:
     *       Math.pow() can introduce rounding errors, especially with large n or large x.
     *       We check b-1, b, and b+1 to account for these artifacts.
     * 
     * @note Time Complexity: O(log² n)
     *       - Loop runs O(log n) iterations (exponents 2 to log₂(n))
     *       - Each iteration performs O(log n) multiplications in power() helper
     * 
     * @note Pedagogical Focus:
     *       - Computing roots algebraically vs numerically
     *       - Handling floating-point precision artifacts
     *       - Loop optimization: checking smallest exponent first ensures largest base
     *       - Defensive programming: boundary checking and overflow protection
     */
    public static TNTPower findPowerDecomposition(long n) {
        if (n <= 0) {
            return null;  // Invalid: non-positive numbers can't be perfect powers
        }

        if (n == 1) {
            return new TNTPower(1, 2);  // 1 = 1^2 (by convention, use smallest x >= 2)
        }

        // Compute maximum exponent: since b >= 2, we need 2^x <= n, so x <= log₂(n)
        // Adding 1 for safety margin due to floating-point rounding
        int maxExponent = (int) (Math.log(n) / Math.log(2)) + 1;

        // Check each exponent from 2 up to maxExponent
        // Starting at x=2 ensures we find the LARGEST base first
        for (long x = 2; x <= maxExponent; x++) {
            // Compute the x-th root: b = n^(1/x)
            double dRoot = Math.pow(n, 1.0 / x);
            long b = Math.round(dRoot);

            // Floating-point arithmetic can introduce small errors
            // Check b-1, b, and b+1 to find the exact match
            if (powerSafe(b - 1, x) == n) {
                return new TNTPower(b - 1, x);
            }
            if (powerSafe(b, x) == n) {
                return new TNTPower(b, x);
            }
            if (powerSafe(b + 1, x) == n) {
                return new TNTPower(b + 1, x);
            }
        }

        // No perfect power representation found
        return null;
    }//end findPowerDecomposition

    /**
     * Finds the smallest base b such that n = b^x for some exponent x >= 2
     * Returns the TNTPower representation with the smallest possible base.
     * 
     * @param n the number to decompose as a perfect power
     * @return TNTPower object representing the smallest base decomposition,
     *         or null if n cannot be expressed as b^x (b > 1, x >= 2)
     * 
     * @example findSmallestBasePowerDecomposition(64) returns TNTPower(2, 6) [since 2^6 = 64, smallest b]
     * @example findSmallestBasePowerDecomposition(27) returns TNTPower(3, 3) [since 3^3 = 27]
     * @example findSmallestBasePowerDecomposition(32) returns TNTPower(2, 5) [since 2^5 = 32, smallest b]
     * @example findSmallestBasePowerDecomposition(17) returns null [17 is prime, can't be perfect power]
     * @example findSmallestBasePowerDecomposition(1) returns TNTPower(1, 2) [1 = 1^2]
     * @example findSmallestBasePowerDecomposition(0) returns null [invalid input]
     * @example findSmallestBasePowerDecomposition(-8) returns null [negative input]
     * 
     * @note Algorithm:
     *       1. Handle edge cases (n <= 0 returns null; n = 1 returns 1^2)
     *       2. Compute maximum exponent as ceiling of log₂(n)
     *       3. For each exponent x from maxExponent DOWN TO 2:
     *          - Compute x-th root using Math.pow(n, 1.0/x)
     *          - Check if floor, exact, or ceiling value satisfies b^x = n
     *          - Return on first success (guarantees smallest b)
     *       4. If no power found, return null
     * 
     * @note Key Difference from findPowerDecomposition:
     *       - findPowerDecomposition loops UP (x=2 to max) → finds LARGEST base
     *       - findSmallestBasePowerDecomposition loops DOWN (x=max to 2) → finds SMALLEST base
     *       - Both find the SAME number represented as a power, just different decompositions!
     * 
     * @note Floating-point precision:
     *       Math.pow() can introduce rounding errors, especially with large n or large x.
     *       We check b-1, b, and b+1 to account for these artifacts.
     * 
     * @note Time Complexity: O(log² n)
     *       - Loop runs O(log n) iterations (exponents max down to 2)
     *       - Each iteration performs O(log n) multiplications in powerSafe() helper
     * 
     * @note Pedagogical Focus:
     *       - Demonstrating multiple valid decompositions of the same number
     *       - Understanding the inverse relationship: larger exponent → smaller base
     *       - Loop direction affects algorithm result without changing correctness
     */
    public static TNTPower findSmallestBasePowerDecomposition(long n) {
        if (n <= 0) {
            return null;  // Invalid: non-positive numbers can't be perfect powers
        }

        if (n == 1) {
            return new TNTPower(1, 2);  // 1 = 1^2 (by convention, use smallest x >= 2)
        }

        // Compute maximum exponent: since b >= 2, we need 2^x <= n, so x <= log₂(n)
        // Adding 1 for safety margin due to floating-point rounding
        int maxExponent = (int) (Math.log(n) / Math.log(2)) + 1;

        // Check each exponent from maxExponent DOWN to 2
        // Starting at max ensures we find the SMALLEST base first
        for (long x = maxExponent; x >= 2; x--) {
            // Compute the x-th root: b = n^(1/x)
            double dRoot = Math.pow(n, 1.0 / x);
            long b = Math.round(dRoot);

            // Floating-point arithmetic can introduce small errors
            // Check b-1, b, and b+1 to find the exact match
            if (powerSafe(b - 1, x) == n) {
                return new TNTPower(b - 1, x);
            }
            if (powerSafe(b, x) == n) {
                return new TNTPower(b, x);
            }
            if (powerSafe(b + 1, x) == n) {
                return new TNTPower(b + 1, x);
            }
        }

        // No perfect power representation found
        return null;
    }//end findSmallestBasePowerDecomposition

    /**
     * Helper method: Safely computes b^x without overflow
     * Returns Long.MAX_VALUE if computation would overflow.
     * This allows the caller to detect overflow safely.
     * 
     * @param b the base
     * @param x the exponent (should be positive)
     * @return b^x, or Long.MAX_VALUE if overflow would occur
     */
    private static long powerSafe(long b, long x) {
        if (b < 0) return Long.MAX_VALUE;  // Negative base in this context is invalid
        if (b == 0) return (x == 0) ? 1 : 0;
        if (b == 1) return 1;
        if (x == 0) return 1;
        if (x == 1) return b;
        if (x > 60) return Long.MAX_VALUE;  // x > 60 guarantees overflow for b >= 2

        // Multiply iteratively, checking for overflow at each step
        long result = 1;
        for (long i = 0; i < x; i++) {
            // Check if next multiplication would overflow
            if (result > Long.MAX_VALUE / b) {
                return Long.MAX_VALUE;  // Overflow detected, return sentinel
            }
            result *= b;
        }
        return result;
    }//end powerSafe

}//end class TNTPower
