I'm trying to solve this problem here in C#:

It is fine if you have leftover blocks, as long as you build a complete pyramid.
Input The first and only line of input contains an integer N (1≤N≤100000000), the number of blocks you have available.
Output Output a single integer – the maximum height of a pyramid that
can be built with at least N blocks. 
Here is my code - please be gentle, I am just learning :)
public static void Main()
{
int bloecke = int.Parse(Console.ReadLine());
int neueBloecke = 1; // Bloecke, die für die neue Ebene benötigt werden
int sumBloecke = 1; // Blöcke in Summe
int seitenLaenge = 1; // Seitenlänge der Ebene
int ebene = 1; // Auf welcher Ebene wir uns aktuell befinden
while (sumBloecke < bloecke)
{
// Wenn wir weniger als 10 Blöcke haben, brauchen wir gar nicht anzufangen > wir haben 1 Ebene
if (bloecke < 10)
{
ebene = 1;
break;
}
// Andernfalls legen wir los
seitenLaenge = 2;
neueBloecke = seitenLaenge * seitenLaenge;
sumBloecke = neueBloecke;
if (sumBloecke>=bloecke)
{
break;
} else
{
ebene ;
}
}
Console.Write(ebene);
}
CodePudding user response:
It looks like you've been just messing with this trying to get it to work. You've complicated it with code that has no real purpose, and now it's confusing.
Your loop has 2 exit conditions when only one is necessary, you have ebene = 1 in there for no reason, etc.
You are taking the wrong approach. If you just mess with your code until it works for whatever tests you're applying, then you'll never really be confident that it works for stuff you didn't test.
You need to prove to yourself that it is correct. Try something like this:
- Ensure that, at the top of the loop, the total block count, base area, and edge length are valid for a pyramid size
ebene 1. (This is called a loop invariant) - Exit the loop at the top if the total number of blocks required by that pyramid is more than you have
- Otherwise, increment
ebeneand calculate the variables for the next size, and loop.
If you implement this simple procedure, then you will be confident that the result is correct.
CodePudding user response:
This works for me:
public static void Main()
{
int availableBlocks = int.Parse(Console.ReadLine());
int newBlocks = 0; // blocks for the new level
int sumBlocks = 0; // sum of used blocks
int edgeLength = 0; // blocks on one side of the level
int level = 0; // which level are we
while (true)
{
// e.g. availableBlocks = 15
//
// edge | new | sum | ok? | level
// 0 0 0 yes 0
// 1 1 1 yes 1
// 3 9 10 yes 2
// 4 16 26 no -
// edgeLength increases by 2, except for the first top-level
if (edgeLength==0)
{
edgeLength ;
} else
{
edgeLength = 2;
}
newBlocks = edgeLength * edgeLength;
sumBlocks = newBlocks;
// Check, if we still have enought blocks
if (sumBlocks <= availableBlocks)
{
level ;
} else
{
Console.WriteLine(level);
break;
}
}
}```

