英文:
I'm trying to print out prime number but not sure what's wrong with my code
问题
我的代码
void printPrimes(int max) {
boolean prime;
for (int n = 2; n < max; n++) {
prime = true;
double maxF;
maxF = Math.sqrt(n);
for (int f = 2; f < maxF; f++) {
if (n % f == 0) {
prime = false;
}
}
if (prime == true) {
System.out.println(n + " 是素数");
}
}
}
这是我得到的结果:
4 是素数
5 是素数
6 是素数
7 是素数
8 是素数
9 是素数
10 是素数
11 是素数
要如何修复这个问题?
英文:
My code
void printPrimes (int max) {
boolean prime;
for (int n = 2; n < max; n++){
prime = true;
double maxF;
maxF = Math.sqrt(n);
for (int f = 2; f < maxF; f++) {
if (n % f == 0) {
prime = false;
}
}
if (prime == true) {
System.out.println(n + " is prime");
}
}
}
This the result I get
4 is prime
5 is prime
6 is prime
7 is prime
8 is prime
9 is prime
10 is prime
11 is prime
what do I do to fix this issue
答案1
得分: 1
调试你的代码。就像拿出一支笔,成为计算机一样。你回答,在不运行这段代码的情况下,它应该做什么。然后使用调试器(或者如果必须的话,使用sysout语句)检查它实际上做了什么。在你发现差异的地方,你找到了一个错误。
例如,Math.sqrt(4),那是什么?比2少2吗?
英文:
Debug your code. As in, take out a pen, be the computer. You answer, without running this code, what it should do. Then check what it actually does with a debugger (or sysout statements if you must). There where you find a difference, you found a bug.
For example, Math.sqrt(4), what's that? is 2 less than 2?
答案2
得分: 0
更改循环中的条件判断:
for (int f = 2; f <= maxF; f++) {
if (n % f == 0) {
prime = false;
}
}
英文:
Change your conditional in your loop
for (int f = 2; f <= maxF; f++) { // should be <= maxf
if (n % f == 0) {
prime = false;
}
}
</details>
# 答案3
**得分**: 0
至少将 `f < maxF` 替换为 `f*f <= max`。
<details>
<summary>英文:</summary>
at least replace `f < maxF` with `f*f <= max`
</details>
# 答案4
**得分**: 0
因为循环最大值应该小于或等于
> Math.sqrt(number)
``` lang-java
public class Main {
public static void main(String[] args) {
printPrimes(20);
}
static void printPrimes (int max) {
for(int i=2; i<=max; i++){
if(isPrime(i)){
System.out.println(i + " 是质数");
}
}
}
static boolean isPrime(int number) {
if(number < 2){
return false;
}
for(int i=2; i<=Math.sqrt(number); i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
英文:
Because loop maximum should be less or equals to
> Math.sqrt(number)
public class Main {
public static void main(String[] args) {
printPrimes(20);
}
static void printPrimes (int max) {
for(int i=2;i<=max;i++){
if(isPrime(i)){
System.out.println(i+" is prime");
}
}
}
static boolean isPrime(int number) {
if(number < 2){
return false;
}
for(int i=2;i<=Math.sqrt(number);i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论