package jvm;
import java.lang.System; // Import System for nanoTime and printf

/**
 * A Java class to replicate the calculation performed by the Python script.
 */
public class Calculation {

    /**
     * Performs the iterative calculation.
     *
     * @param iterations The number of iterations for the loop.
     * @param param1     The first parameter used in the calculation.
     * @param param2     The second parameter used in the calculation.
     * @return The result of the calculation.
     */
    public static double calculate(int iterations, int param1, int param2) {
        // Initialize the result as a double
        double result = 1.0;

        // Loop from 1 to iterations (inclusive)
        for (int i = 1; i <= iterations; i++) {
            // Calculate the first value of j
            // Use double for j to ensure floating-point arithmetic
            double jMinus = (double)i * param1 - param2;
            // Subtract 1.0 / jMinus from the result (use 1.0 for double division)
            result -= (1.0 / jMinus);

            // Calculate the second value of j
            double jPlus = (double)i * param1 + param2;
            // Add 1.0 / jPlus to the result
            result += (1.0 / jPlus);
        }
        // Return the final calculated result
        return result;
    }

    /**
     * The main entry point of the program.
     *
     * @param args Command line arguments (not used).
     */
    public static void main(String[] args) {
        // Define the parameters for the calculation
        final int ITERATIONS = 100_000_000; // Use underscore for readability (Java 7+)
        final int PARAM1 = 4;
        final int PARAM2 = 1;

        // Record the start time using System.nanoTime() for higher precision
        long startTime = System.nanoTime();

        // Perform the calculation and multiply the result by 4.0
        double finalResult = calculate(ITERATIONS, PARAM1, PARAM2) * 4.0;

        // Record the end time
        long endTime = System.nanoTime();

        // Calculate the duration in nanoseconds
        long durationNanos = endTime - startTime;
        // Convert the duration to seconds (as a double)
        double durationSeconds = durationNanos / 1_000_000_000.0;

        // Print the final result, formatted to 12 decimal places
        System.out.printf("Result: %.12f%n", finalResult);
        // Print the execution time, formatted to 6 decimal places
        System.out.printf("Execution Time: %.6f seconds%n", durationSeconds);
    }
}
