我发现了一个有趣的问题,我想我可以尝试做;我几乎立即发现了一个我似乎无法解决的问题。
当我运行我的代码时,没有错误,但它只是运行而不返回任何内容。我的循环似乎没问题,而且我知道我的查找素数的算法有效,所以我不知道出了什么问题。
经过大量编辑后,我仍然遇到同样的问题,但是当在 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;
}
}
}
}