布尔返回值不被接受在素数检查方法中。

huangapple go评论68阅读模式
英文:

Boolean return value not accepted in prime check method

问题

以下是翻译好的部分:

我是一个Java初学者,但我在Python方面有一些经验。为了学到更多,我尝试在Java中重新创建一些我以前在Python中做过的事情,以了解它们之间的区别。我的想法是创建一个方法,用于检查给定的整数参数是否是质数。再次强调,这可能可以更轻松/更高效地完成,但我将其视为一种训练练习。这就是为什么我使用了两个不同的for循环(只是为了使用for循环的缘故)。

然而,我希望该方法返回true或false。
当我像下面我的代码中声明它时,我会得到一个异常(未解决的编译问题),因为我的方法应该返回一个布尔值。
如果我将方法更改为void,我会得到一个错误,说我的方法不应该返回任何东西。

所以是什么情况... 它是否返回了某些内容?为什么这不被视为返回布尔值呢?

我使用Win10和Eclipse IDE。

谢谢!

PS:这也是为了尝试如何正确设置数组,因为我对它们一窍不通。

代码如下:

public class AB4Funk {
    public static boolean ab40(int n) {
        int x = n/2+1;
        int[] array = new int[x];
        for(int i=2; i<x; i++) {
            array[i-2]=i;
        }
        for(int zahl : array) {
            if(n%zahl==0) {
                return true;
            }
            else {
                return false;
            }
        }
    }
}

经过一些非常有帮助的评论后,我的新代码如下:

public class AB4Funk {
    public static boolean ab40(int n) {
        // int x = n/2+1;
        int[] array = new int[n];
        for(int i=2; i<n; i++) {
            array[i-2]=i;
        }
        for(int zahl : array) {
            if(n%zahl==0) {
                return false;
            }
        }
        return true;
    }
}

这个新代码会导致除零错误,我无法定位错误的来源。(为了调试,我注释掉了x(我实际上不需要)以查看它是否是错误的来源)。

英文:

I am a java beginner but I have a bit of experience in python. To learn more, I try to recreate some of the things I did in python in java to see how it is different. My idea: create a method that checks whether a given integer parameter is a prime number. Again, this can probably be done easier/more efficient etc., but I see it as a training exercise. This is why I do it with two different for loops (so just for the sake of using for loops 布尔返回值不被接受在素数检查方法中。 ).
However, I want the method to return true or false.
When I declare it as in my code below, I get an exception (unsresolved compilation problem), because my method should return a boolean value.
If I change the method to void, I get an error saying my method isn't supposed to return anything.

So what is it... is it returning something or not? And why does this not count as returning a boolean?

I use Win10 and the eclipse IDE.

Thank you!

PS: This is also to try out how to properly set up arrays, as I have zero experience with them.

The Code:

public class AB4Funk {
    public static boolean ab40(int n) {
	    int x = n/2+1;
	    int[] array = new int[x];
	    for(int i=2; i<x; i++) {
		    array[i-2]=i;
	    }
	    for(int zahl : array) {
		    if(n%zahl==0) {
			    return true;
		    }
		    else {
		    	return false;
		    }
	    }
	
    }
}

After some very helpful comments, my new code is:

public class AB4Funk {
	public static boolean ab40(int n) {
		//int x = n/2+1;
		int[] array = new int[n];
		for(int i=2; i<n; i++) {
			array[i-2]=i;
		}
		for(int zahl : array) {
			if(n%zahl==0) {
				return false;
			}
		}
		return true;
		
	}
}

Which gives me a division by zero error, which I cannot locate. (for debugging I commented out the x (which I don't really need anyways) to see if it is the source of my error)

答案1

得分: 2

你的方法存在两个主要问题:

  • 可能永远不会执行循环,例如,如果输入的数字小于2,则方法永远不会返回任何内容。
  • 如果循环执行,方法将在第一次迭代后返回 truefalse,即在测试第一个潜在的除数后返回。

你可以通过将 return false 移动到循环之后来解决这两个问题,即如果数字不能被 任何 这些数字整除。

此外,你可以考虑颠倒 truefalse,因为你想测试一个数字是否 素数,并相应地调用你的方法。最后,你不必首先将所有潜在的除数存储在数组中,而可以直接测试它们。

public static boolean prime(int n) {
    int x = n / 2 + 1; // 实际上,测试到 x = sqrt(n) 就足够了
    for (int zahl = 2; zahl < x; zahl++) {
        if (n % zahl == 0) {
            return false; // 不是素数
        }
    }
    return true; // 是素数
}

如评论中所述,你可能还想将要测试的数字的上限 xn/2 更改为 sqrt(n)(或者反过来,在循环中更改检查为 zahl * zahl <= n)。毕竟,如果数字可以被大于 sqrt(n) 的数字整除,那么它也必须被小于 sqrt(n) 的数字整除。这可能看起来像在测试了2之后跳过偶数除数的微小改进,但实际上相当于将一个O(n²)算法改进为O(n),对于测试较大的数字来说相当重要。

英文:

There are two main problems with your method:

  • it is possible that the loop is never executed, e.g. if the input number is smaller than 2, thus resulting in the method never returning anything
  • if the loop is executed, the method will return true or false after the very first iteration, i.e. after testing the first potential divisor

You can fix both problem by moving the return false after the loop, i.e. if the number is not evenly divisible by any of those numbers.

Also, you may consider inverting true and false, since you want to test whether a number is prime, and also call your method accordingly. Finally, you do not have to store all the potential divisors in an array first but can just test them directly.

public static boolean prime(int n) {
    int x = n/2+1; // actually, testing until x = sqrt(n) would be enough
    for (int zahl = 2; zahl &lt; x, zahl++) {
        if (n % zahl == 0) {
            return false; // not prime
        }
    }
    return true; // is prime
}

As mentioned in comments, you may also want to change the upper bound x for numbers to test from n/2 to sqrt(n) (or, conversely, change the check in the loop to zahl * zahl &lt;= n). After all, if the number is evenly divisible by a number &gt; sqrt(n), it also has to be evenly divisible by a number &lt; sqrt(n). This may seem like a minor improvement, like skipping even divisors after having tested for 2, but it's actually equivalent to changing an O(n²) algorithms to O(n) and quite significant for testing larger numbers.

huangapple
  • 本文由 发表于 2020年8月10日 18:13:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63338205.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定