How to find the next number in the series 1, 8, 27, 64, 125, 216 using Java

1 Answer

0 votes
import java.util.List;

/**
    This program finds the next number in a sequence of perfect cubes.
    The input series is: 1, 8, 27, 64, 125, 216

    These values correspond to:
    1^3, 2^3, 3^3, 4^3, 5^3, 6^3

    The next value is 7^3 = 343.

    The approach:
    - Verify each number is a perfect cube.
    - Extract the cube root of the last number.
    - Compute (root + 1)^3 to get the next number.
*/

public class NextCube {
    // Check whether a number is a perfect cube.
    // Uses Math.cbrt and Math.round to verify the cube root.
    static boolean isPerfectCube(int value) {
        double root = Math.cbrt(value);          // cube root
        int rounded = (int) Math.round(root);    // nearest integer
        return rounded * rounded * rounded == value;
    }

    // Compute the next cube in the series.
    static int nextCubeInSeries(List<Integer> series) {
        int lastValue = series.get(series.size() - 1);

        // Compute the integer cube root of the last value.
        int lastRoot = (int) Math.round(Math.cbrt(lastValue));

        // The next number is (lastRoot + 1)^3.
        int next = (lastRoot + 1) * (lastRoot + 1) * (lastRoot + 1);
        return next;
    }

    public static void main(String[] args) {

        List<Integer> series = List.of(1, 8, 27, 64, 125, 216);

        // Validate the pattern before computing the next value.
        for (int value : series) {
            if (!isPerfectCube(value)) {
                System.err.println("Series contains a non-cube value.");
                return;
            }
        }

        int nextValue = nextCubeInSeries(series);

        System.out.println("Next number in the series: " + nextValue);
    }
}


/*
run:

Next number in the series: 343

*/

 



answered Aug 20 by avibootz
...