G
Guest
Gast
Hallo an alle...
Also hab hier ein Programm das nicht so richtig
funktionieren will.
Es soll für eine beliebige natürliche Zahl n die kleinste Primzahl
liefern, die größer oder gleich n ist.
Der Algorithmus zum Bestimmen, ob es eine Primzahl ist, müsste richtig sein.
Das Problem ist, dass er im hauptteil nicht "weiterzählt"... bitte helft mir
import algds.IOUtils;
public class NächstePrimzahl{
public static boolean result=true; //Annahme Zahl ist eine Primzahl
static int n;
public static boolean nextprim(int n){
if (n<2) result=false;
else
if (n==2) result=true;
else
for (int i=2 ; i*i<n; i++) // i rennt nur bis Wurzel n!
if (n % i == 0)
{
result=false;
}
else {
result=true;
}
return(result);
}
public static void main (String[] args){
System.out.println("Geben sie eine natuerliche Zahl ein: ");
int zahl=IOUtils.readInt();// <--- zu pruefende Zahl
if (nextprim(zahl)==true) {
System.out.println("Die nächste Primzahl ist: "+zahl);
}
else {
while (nextprim(zahl)==false){
zahl++;
nextprim(zahl);
}
}
}
}
Also hab hier ein Programm das nicht so richtig
funktionieren will.
Es soll für eine beliebige natürliche Zahl n die kleinste Primzahl
liefern, die größer oder gleich n ist.
Der Algorithmus zum Bestimmen, ob es eine Primzahl ist, müsste richtig sein.
Das Problem ist, dass er im hauptteil nicht "weiterzählt"... bitte helft mir
import algds.IOUtils;
public class NächstePrimzahl{
public static boolean result=true; //Annahme Zahl ist eine Primzahl
static int n;
public static boolean nextprim(int n){
if (n<2) result=false;
else
if (n==2) result=true;
else
for (int i=2 ; i*i<n; i++) // i rennt nur bis Wurzel n!
if (n % i == 0)
{
result=false;
}
else {
result=true;
}
return(result);
}
public static void main (String[] args){
System.out.println("Geben sie eine natuerliche Zahl ein: ");
int zahl=IOUtils.readInt();// <--- zu pruefende Zahl
if (nextprim(zahl)==true) {
System.out.println("Die nächste Primzahl ist: "+zahl);
}
else {
while (nextprim(zahl)==false){
zahl++;
nextprim(zahl);
}
}
}
}