>编辑
我想创建一个 java 程序,该程序输出所有小于给定数字的素数,n
提示作为输入给用户。挑战在于编写一个函数,该函数将在一行中执行此操作。它并没有使它成为一个更好的代码,但仍然是一个有趣的挑战。
我从我的main
方法开始,我要求用户输入并将其作为我的Primes(int number, int divisor)
方法的参数传递。此方法采用两个参数,number
和divisor
。该方法检查number
是否可以被divisor
整除。如果后者不划分前者,则该方法使用divisor = divisor - 1
再次调用自身,直到the divisor = 1
。万岁,我们找到了一个质数。因此,我必须打印它,并且必须再次使用number = number - 1
和divisor = number - 2
调用我的方法。我必须这样做,因为我必须检查每个小于number
的素数。
Primes(number-1, number-2)
.
一个方法是否可以返回一个值并同时调用另一个方法?我需要这样的东西:
...condition ? do smth : return n && Primes(smth)...
如果我不够清楚,请告诉我。 提前感谢,
这是我的代码。它看起来很奇怪,但如果你花时间看一下它,它真的很简单:
import java.*;
import java.util.Scanner;
public class Main {
public static int Primes(int n, int k) {
return ((k == 0) ? n : (k == 1 && n == 1)
? n : (k == 1 && n > 1)
? Primes(n-1, n-2) : (n % k) != 0
? Primes(n, k-1) : Primes(n-1, n-2));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int num = s.nextInt();
System.out.println("The primes are: " + Primes(num, (num-1)));
}
}
我找到了解决我挑战的方法。看看你是否有兴趣,尽管我知道这不是最佳的。由于我找不到return n && Primes(smth)
的方法,我做了一个新的方法PrintPrimes(int n)
可以打印n
并调用Primes(n-2, n-3)
。在这里:
import java.*;
import java.util.Scanner;
public class Main {
public static int Primes(int n, int k) {
// Check if k and n are lower than 2 we're done because we've checked every number from n all the way down to 1
// If k is 1 and n is greater than 1 we've found a prime and have to print it
// If n modulo k yields 0 then n is not prime. We call the method again with n = n - 1
// If n mod k is different than 0, we call the method again with k = k - 1
return ((k < 2 && n < 2) ? PrintPrimes(n) : (k == 1 && n > 1)
? PrintPrimes(n) : (n % k) != 0
? Primes(n, k-1) : Primes(n-1, n-2));
}
public static int PrintPrimes(int n) {
System.out.println(n);
return ((n == 1) ? n : Primes(n-2, n-3));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int num = s.nextInt();
Primes(num, (num-1));
}
}
这效果很好