import java.util.Scanner;
public class Primzahl {
public static void main(String[] args) {
boolean ergebnis = false; // Abfragen ob Ergebnis wahr oder falsch
int i;
int n; // Variablen deklarieren
Scanner scanner = new Scanner(System.in); // Scanner aufrufen
System.out.println("Bitte geben Sie die erste zu untersuchende Zahl ein: \n");
n = scanner.nextInt();
System.out.println(" \nEs wird nun überprüft, ob die Zahl " + n + " eine Primzahl ist: \n");
for (i = 2; i < n; i++) { // Zählvariable; Bedingung; Schrittweite
if ((n % i) == 0) // Wenn n mod 2 = 0
{
ergebnis = true;
}
}
if (ergebnis == false) {
System.out.println("Die eingegebene Zahl ist eine Primzahl");
}
else {
System.out.println("Die eingegebene Zahl ist keine Primzahl");
}
scanner.close();
}
}
I try to write a code which is checking if its a prime number or not. But I don't get the logic.
Question: Why is 0 or 1 still a prime number and how can i fix that?
You code will only mark a number as "not prime", ie ergebnis = true
is if you find a divisor that's equal or greater than two. Obviously, neither 0
nor 1
has such a divisor.
So just add an extra check whether the number is smaller than two:
if (n < 2) {
ergebnis = true; // meaning 'not prime'
}
(By the way: terrible choice of variable name. Does ergebnis
(German for "result") mean that the result is "it's prime" or "not a prime"?)
Also, you could improve your comments: instead of just repeating what the code does, explain why it does it and what it means. Eg, instead of
if((n%i)==0) //Wenn n mod 2 = 0
how about
if((n%i)==0) //divisor found -> not a prime
Add n>1
condition.
Then it will give the right result for 0 , 1 and negative numbers too!
import java.util.Scanner;
public class Primzahl {
public static void main(String [] args) {
boolean ergebnis=false; //Abfragen ob Ergebnis wahr oder falsch
int i;
int n; //Variablen deklarieren
Scanner scanner = new Scanner(System.in); //Scanner aufrufen
System.out.println("Bitte geben Sie die erste zu untersuchende Zahl ein: \n");
n=scanner.nextInt();
System.out.println(" \nEs wird nun überprüft, ob die Zahl " + n + " eine Primzahl ist: \n" );
for (i=2;i<n;i++){ //Zählvariable; Bedingung; Schrittweite
if((n%i)==0) //Wenn n mod 2 = 0
{
ergebnis=true;
}}
if (ergebnis==false && n>1)
{
System.out.println("Die eingegebene Zahl ist eine Primzahl");
}
else
{
System.out.println("Die eingegebene Zahl ist keine Primzahl");
}
scanner.close();
}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.