我在 java 中的一行质数函数有什么问题?

What is wrong with my one line prime function in java?

编辑

我想创建一个 java 程序输出所有小于给定数字 n 的素数提示作为输入给用户。挑战在于编写一个函数来 在一行 中完成此操作。它并没有使它成为更好的代码,但仍然是一个有趣的挑战。

我从我的 main 方法开始,我要求用户输入并将其作为我的 Primes(int number, int divisor) 方法的参数传递。此方法有两个参数,numberdivisor。该方法检查 number 是否可以被 divisor 整除。如果后者不划分前者,该方法将再次调用自身 divisor = divisor - 1 直到 the divisor = 1。欢呼,我们找到了一个质数。因此,我必须打印它 并且 必须使用 number = number - 1divisor = number - 2 再次调用我的方法。我必须这样做,因为我必须检查每个小于 number.

的素数

Primes(number-1, number-2).

一个方法return一个值是否可以同时调用另一个方法?我需要这样的东西:

    ...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));
    }
    
}

这很有效