Question - Java: Pyramid layers
The top of the pyramid contains one brick. 2nd layer has 1 + 2 = 3 bricks. 3rd layer has 1 + 2 + 3 = 6 bricksh. …. nth layer has 1 + 2 + … + n bricks. Given the number of bricks you have, calculate the maximum number of layers you can build. My code: static void calculateHeight(long n) { double layers = 0, part1, part2, part3; double k = 0; k = (162 * n) / (2 * Math.sqrt(27)); part1 = (Math.sqrt(3) * Math.abs(k) / (3 * k)); part2 = Math.cbrt(Math.abs(k) + Math.sqrt((k * k) - 1)); part3 = Math.cbrt(Math.abs(k) - Math.sqrt((k * k) - 1)); layers = part1 * (part2 + part3) - 1; System.out.print((long) layers + " "); } Problem: When I enter 658, the correct output would be 14 (14.826), but when I enter 286 it shows 10 (10.9999), not 11 (correct output). So if I use Math.round the other answers would be incorrect, so how can I fix that?