G
gateway_2_hell
Gast
Hallo!
Ich sitze im Moment an dieser Aufgabe:
Es geht darum, einen rekursiven "Primzahlentester" zu schreiben.
So weit bin ich im Moment. Das Programm funktioniert auch schon, nur ein Sonderfall ist noch nicht bedacht: N = 1. In diesem Fall soll ja false zurückgegeben werden.
Ich möchte das Programm möglichst mit nur einem Ausgang (--> return) schreiben.
Kann mir wer nen Tipp geben?
Vielen Dank für eure Hilfe![/code]
Ich sitze im Moment an dieser Aufgabe:
Exercise 1
A prime number is an integer that cannot be divided by any integer other than one and itself. For example, 7 is prime because its only divisors are 1 and 7. The integer 8 is not prime because its divisors are 1, 2, 4, and 8.
Another way to define prime is:
prime(N) = prime(N, N-1)
prime(N, 1) = true
prime(N, D) = if D divides N, false
else prime(N, D-1)
For example,
prime(4) = prime(4,3)
prime(4,3) = prime(4,2)
prime(4,2) = false
Another example,
prime(7) = prime(7,6)
prime(7,6) = prime(7,5)
prime(7,5) = prime(7,4)
prime(7,4) = prime(7,3)
prime(7,3) = prime(7,2)
prime(7,1) = true
Translate the math-like definition of prime into two Java methods that return boolean. Use the % operator to test divisibility. Put your method into a class, write a testing class, and test your program. (Look at FactorialTester.java in this chapter.)
If you run your program for integers larger than about 12,000 (on a Windows system) you will run out of memory. Your program will stop running and report a StackOverflowError. This is because each activation in the activation chain requires some memory, and 12,000 activations uses up all the memory that has been reserved for this use.
Es geht darum, einen rekursiven "Primzahlentester" zu schreiben.
Code:
public class PrimeTester
{
private prime prim;
public boolean PrimeTester(int N)
{
prim = new prime();
return prim.istPrimzahl(N, N-1);
}
}
Code:
public class prime
{
public boolean istPrimzahl(int N, int D)
{
boolean rg = true;
if(N == 1) // Eins ist keine Primzahl!
rg = false;
if(D == 1)
rg=true;
else if (N % D == 0) //Wenn sie Teilbar ist, ist die Zahl auch keine Primzahl / Bei N=1 stürzt das Programm hier ab (Division durch 0...)
rg = false;
else
rg = istPrimzahl(N, D-1);
return rg;
}
}
So weit bin ich im Moment. Das Programm funktioniert auch schon, nur ein Sonderfall ist noch nicht bedacht: N = 1. In diesem Fall soll ja false zurückgegeben werden.
Ich möchte das Programm möglichst mit nur einem Ausgang (--> return) schreiben.
Kann mir wer nen Tipp geben?
Vielen Dank für eure Hilfe![/code]