我发现了一个有趣的问题,我想我可以尝试做一下;我几乎立刻就发现了一个问题,但我似乎无法解决这个问题。
当我运行代码时,没有错误,但它只是运行而不返回任何内容。我的循环似乎没问题,而且我知道我的查找素数的算法有效,所以我不知道出了什么问题。
经过大量编辑后,我仍然遇到同样的问题,但是当在 python 中运行几乎相同的代码时,python 代码运行并实际上返回结果。这是更改后的代码:
public class PrimeNumtoPi {
static double pi = Math.PI;
static double accuracy = 0.1;
static int range = 10000;
//checks whether an int is prime or not.
static boolean isPrime(int n) {
if(n % 2 == 0) {
return false;
} else {
int i = 3;
while (i < n / 2) {
if(n % i == 0) {
return false;
}
i += 2;
}
}
return true;
}
public static int nearestwhole(double n) {
double remainder = n%1;
if(remainder >= 0.5) {
return (int) (n - remainder + 1);
} else {
return (int)(n - remainder);
}
}
public static boolean isClose(double n) {
if(abs(n - pi) < accuracy) {
return true;
} else {
return false;
}
}
public static double abs(double n) {
if(n < 0) {
return n * -1;
} else {
return n;
}
}
public static void main(String[] args) {
int current = 3;
while(current <= range) {
int numerator = nearestwhole(current * pi);
if (isPrime(numerator)) {
if(isClose(numerator/current) == true) {
System.out.println(numerator + " and " + current);
}
}
current += 2;
while(isPrime(current) == false) {
current += 2;
}
}
}
}
最佳答案
在谈论 double 时,您不能期望完美的准确性, double 不是实数(或有理数)。
请记住,在任何(非平凡)范围内都有无限数量的有理数,但表示它们的位数却有限。
因此,比较两个 double 的同一性 (==) 很少会返回想要的结果。
出于您的目的,有效的替代方案可以使用 java 的 BigDecimal类,它可以让您控制所需的精度级别。
有关更多信息,您可能需要阅读wikipedia page double 和/或 this article
<小时/>此外,似乎b
和j
总是一起增加,这是这里的另一个问题。强力解决方案将有 2 个嵌套循环,每个循环增加一个变量,而不是 1 个循环同时增加两个变量。
关于优化的评论:您可能想使用sieve of eratosthenes提高查找素数的效率。
关于java - 找到除以 Pi 后等于小数点后 4 位的最小素数? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11946943/