我一直在尝试创建一个永远列出素数的类。我知道这已经完成了,但我想我在我的试验中学到了一些有价值的原则。
这个项目帮助我更好地理解了返回值、方法参数、简单的数学算法,以及我个人喜欢使用的是for和if/else语句的强大功能。
我希望您能深入了解可以提高代码性能和/或代码结构任何明显缺陷的改进。
//first the class is declared
public class startListingPrimeNumbers {
// method is created to start the prime number listing from 1 to infinity
// and beyond
public void startFromOneListingPrimeNumbers() {
// Create the primary for loop using doubles so the program will
// continue on infinitely
for (double x = 1; x > 0.000; x = x + 1.000) {
// The double c is for determining numbers that only have 2 factors
// are prime
double c = 2.000;
// I use the primeLogger to keep track of each numbers amount of
// factors it contains, to later compare this value to c to know if
// it's prime or not
double primeLogger = 0.000;
// the multiplier is used to iterate through the for loop below
double multiplier;
// this is the bread and butter, I take multiplier and iterate it
// until it is greater than x, if a remainder exists from x divided
// by multiplier then my primeLogger adds nothing to itself
// if there is no remainder then primeLogger adds one, meaning
// multiplier is a factor of x.
for (multiplier = 1.000; multiplier <= (x); multiplier = multiplier + 1.000) {
if (x % multiplier == 0) {
primeLogger = primeLogger + 1.000;
} else {
primeLogger = primeLogger + 0.000;
}
}
// here we see if there are only 2 factors for x, and the console
// prints the number
if (c == primeLogger) {
System.out.println(x + " is a prime number");
}
// primeLogger is set back to zero to go on to the next x value
// based on the primary for loop description
primeLogger = 0.000;
}
}
}发布于 2014-03-07 04:44:56
这里的主要问题是使用不精确的浮点值。它不仅减缓了整个过程(小故障),而且一旦值通过字段宽度的积分截止值,就会产生不正确的结果。如果你真的想让计算接近无穷大(或者什么? 24位?)您需要切换到BigInteger,它可以对任意大小的“精确”整数进行建模。
好的,他们可能限制在一个非常,非常大的number...much比双倍,但很可能会持续超过你的个人电脑的寿命。
这个问题对解决方案的正确性至关重要,因此我将把它留给自己,并将任何其他的审查问题留给其他人。
发布于 2014-03-07 07:03:25
for循环中声明乘法器。用于(双乘数= 1.000;乘数<= (x);乘数=乘数+ 1.000) {(有效的Java,第二版,项目45:最小化局部变量的范围)PrimeGenerator可能是这个类的好名称。发布于 2014-03-07 07:34:14
@DavidHarkness和@palacsint警告说,由于精度的原因,double的错误使用是普遍存在的,但是我想知道为什么在寻找素数时你会考虑它呢?你知道任何非整数素数吗?
好的,所以你说-我想要它能计算出非常大的数字,而我没有意识到截止。但是为什么使用double来表示c (常量2.000)?还是为primeLogger?它降低了代码的可读性,因为它意味着非整数。就我个人而言,在质数算法中,所有的1.000000都让我头晕-- 1.0已经足够了.
其他一些问题:
无限的循环-
for (double x = 1; x > 0.000; x = x + 1.000) {非常笨重,很难读懂
for (double x = 1; ; x++) {做同样的,更容易的眼睛
在您的算法中,迭代所有小于x的数字,计算其所有除数,然后检查是否有少于两个这样的值。
这是一个非常低效的算法--你应该停止数到2!大的数字可能有成千上万的除数,但你只需要一个知道他们不是素数!
更重要的是,您将1计算为除数。因为我不知道没有1作为除数的任何素数,所以可以跳过它,然后寻找任何非1除数来得出这个数不是素数。
primeLogger = 0.000;是完全多余的,因为您在块中声明它,并在它的开头设置它。没必要“重置”它。
@palacsint提到了多余的评论,我想补充的是,当注释多于代码时,这是一种难闻的味道--您的代码应该足够描述,以便读者能够理解:
// I use the primeLogger to keep track of each numbers amount of
// factors it contains, to later compare this value to c to know if
// it's prime or not
double primeLogger = 0.000;...this可能意味着primeLogger不是个好名字..。numOfFactors怎么样?不需要解释..。
https://codereview.stackexchange.com/questions/43668
复制相似问题