Search code examples
javaloopsfor-loopmathperfect-square

How to create loop that runs through Square Pyramidal equation


Pretty new to Java. I'm trying to create code that finds out which square pyramidal number is itself a perfect square.

The square pyramidal number basically refers to the total number of balls in a pyramid that has a layer number of n. I'm looking for n whose total number of balls is a perfect square. I've figured it out mathematically (there are only two values of n that work--1 and 24, which produce a square pyramidal number of 1 and 4900, respectively), but I don't know how to make code that will figure it out automatically.

This is the code that I have right now, which requires inputting integers into n in order to find your answer. I'm trying to figure out how to make a loop that will produce the answers of 1 and 24 on it's own.

class SquarePyramidalNumber
{
    public static void main(String[] args)
    {
        double t,n=24;
        t=(n*(n+1)*(2*n+1))/6;
        System.out.println("\n");
        System.out.println("Layer number = " + n );
        System.out.println("Number of balls in layer = " + n*n );
        System.out.println("Total number of balls = " + t );
        System.out.println("Square root of total number of balls = " + Math.sqrt(t) );
        System.out.println("\n");
    }
}

Hopefully I explained myself well! Thank you for any and all help.


Solution

  • First of all, you will notice that each layer of balls in the pyramid is formed by a number of balls that is a perfect square (1, 4, 9, 16, ...) So the total number of balls of a pyramid that has a base of, lets say n balls, the pyramid number is going to be

    n + 
    (sqrt(n)-1)^2 +
    (sqrt(n)-2)^2 +
    .. +
    1
    

    So, start by splitting your problem. First of all, you have to know if a number is a pyramid, so let's create a method like this:

    private boolean isPyramid(int n) 
    

    You also have to know if a number is a perfect square:

    private boolean isPerfectSquare(int n)
    

    after filling these methods, you could just loop and look for the numbers that fulfil both conditions:

    int i=1;
    while(true){ //this will run forever so be careful
      if (isPyramid(i) && isPerfectSquare(i)){
        System.out.println("Found one! "+i);
      }
      i++;
    }
    

    Now, your task is to fill both methods with code :)