+ 2

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?

3rd Feb 2023, 2:20 PM
Lily
11 Respuestas
+ 3
For this reason you have to solve a cubic equation.
5th Feb 2023, 2:28 PM
JaScript
+ 3
An idea will be to rewrite the code in Javas high-precision arithmetic with BigDecimal etc.
5th Feb 2023, 4:50 PM
JaScript
+ 3
I tried it with BigDecimal out. For the above mentioned examples it worked.
6th Feb 2023, 8:12 AM
JaScript
+ 3
I have found in web Newton solver for cubic equations and the results are similar to this.
8th Feb 2023, 8:17 AM
JaScript
+ 3
8th Feb 2023, 6:44 PM
JaScript
+ 3
Lily , As you have already written the solutions for the equation are scattered on both sides to the results you expect. Therefore, I think that the outputs must then be inserted into the equation, and tested what number of bricks is really needed. This can be determined with a simple algorithm similar to the one in my first code. I don't see any other approach that can get around this. Could you please give us feedback what is the current status here?
10th Feb 2023, 3:38 PM
JaScript
+ 2
Can you add your logic for calculations..? Round, ceil, floor none works for that.
3rd Feb 2023, 5:11 PM
Jayakrishna 🇮🇳
+ 1
I did it but it gave me the problem above
5th Feb 2023, 4:03 PM
Lily
0
There is a hint for that problem brick=(n*(n+1)*(n+2))/6 with n is layer. From that I have 6*brick=n^3+3n^2+2n and solve n to find layer
5th Feb 2023, 11:16 AM
Lily
0
https://code.sololearn.com/c8x3fGqnc43A/?ref=app It is quite new to me. Would you mind demonstrating it on my code, please?
6th Feb 2023, 11:22 AM
Lily
0
The task description says about sum of n numbers. The hint is about sum of squires of n numbers. And your calculations for part1, part2, part3 are unknown to me.. So sry, question and answers are unknown to me.. Can you add the calculations details.?.
7th Feb 2023, 9:12 PM
Jayakrishna 🇮🇳
En tendencia hoy
Be honest