[英]Why is 1 or 0 still a Prime number?
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?问题:为什么 0 或 1 仍然是质数,我该如何解决?
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.您的代码只会将一个数字标记为“非素数”,即
ergebnis = true
是如果您找到一个等于或大于 2 的除数。 Obviously, neither 0
nor 1
has such a divisor.显然,
0
和1
都没有这样的除数。
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"?) (顺便说一句:变量名称的糟糕选择
ergebnis
(德语为“结果”)是否意味着结果是“它是素数”或“不是素数”?)
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.添加
n>1
条件。
Then it will give the right result for 0 , 1 and negative numbers too!然后它也会为0 、 1和负数给出正确的结果!
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();
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.