Reputation: 55
I want to calculate prime numbers with a recursive function called primzahlenRekursiv
, but I get a StackOverflowException
in the function istPrimzahl
, where I check if the current number is prime.
static void Main(string[] args)
{
primzahlenRekursiv(2);
}
static void primzahlenRekursiv(int primzahl)
{
if (istPrimzahl(primzahl, 2)) { Console.Writeline(primzahl); }
primzahlenRekursiv(primzahl + 1);
}
static bool istPrimzahl(int primzahl, int zahl)
{
if (primzahl % zahl != 0) { istPrimzahl(primzahl, zahl + 1); }
if (primzahl == zahl) { return true; }
return false;
}
Upvotes: 0
Views: 648
Reputation: 14007
You have nothing in your recursive code that will ultimately end the recursion:
static void primzahlenRekursiv(int primzahl)
{
if (istPrimzahl(primzahl, 2)) { Console.Writeline(primzahl); }
primzahlenRekursiv(primzahl + 1);
}
primzahlenRekursiv
always calls itself without any condition to stop it. Since any method call needs space on the stack, your algorithm will run until your stack runs out. Hence your exception.
In fact there is no need to run your algorthim recursively:
for (var kandidat = 2; ; kandidat++) {
if (istPrimzahl(kandidat, 2)) { Console.Writeline(kandidat); }
}
This will run your code in an endless loop and not use up your stack that quickly. But be careful, eventually you will still run into a stack overflow exception if your candidate is getting high enough (you are still running recursion in istPrimzahl
), just later. Therefore you better constrain your number set (in this example to 10000):
for (var kandidat = 2; kandidat < 10000; kandidat++) {
if (istPrimzahl(kandidat, 2)) { Console.Writeline(kandidat); }
}
Also, in your code your recursion is not running correctly because of another error:
if (primzahl % zahl != 0) { istPrimzahl(primzahl, zahl + 1); }
...does not use the result of the recursive call. You are probably meaning to return the result of the recursive call at this spot.
Another solution would of course be a tail call, but C# doesn't support that (althogh IL would).
Upvotes: 1