java - 打印前 N 个素数

标签 java

<分区>

语句是:写一个程序,读取一个整数N并打印前N个素数。

public static void main(String[] args) 
{
    Scanner scan = new Scanner(System.in);

    int N = scan.nextInt();
    int x = 2;

    for(int i = 0; i <= N; i++)
    {
        int count = 0;

        for(int j = 1; j <= x; j++)
            if(x%j == 0)
                count++;

        if(count == 2)
            System.out.print(x + " ");

        x++;
    }
}

当我运行这段代码时,它没有给我确切的 N 个数字。例如,对于 N=1 & 2,它打印前 2 个质数,对于 N = 3 & 4,它打印前 3 个质数,对于 N = 5 & 6,它打印前 4 个质数,依此类推。这段代码有什么问题?

最佳答案

我认为你的程序有很多缺陷需要修复,所以我决定写一个更简单、更优雅的程序。

Scanner scan = new Scanner(System.in);
int N = Integer.parseInt( scan.nextLine());
int count = 0;
int num = 2;
while(count != N) { // while count!= number of prime numbers entered keep searching..
    boolean prime = true;// to determine whether the number is prime or not
    for (int i = 2; i <= Math.sqrt(num); i++) { //efficiency matters
        if (num % i == 0) {
            prime = false; // if number divides any other number its not a prime so set prime to false and break the loop.
            break;
        }

    }
    if (prime) {
        count++;
        System.out.println(num);
    }
    num++; see if next number is prime or not.
}

关于java - 打印前 N 个素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33725505/

相关文章:

java - 隐式 super 构造函数 StudentTest() 未定义。必须显式调用另一个构造函数”

java - 为什么提升失败和并发模式失败?

java - 获取 BufferedImage 的每像素位数

java - 如何将多个 java.awt.image.BufferedImage 传递给 Matlab

java - 使用同步锁时的困惑

java - hibernate/JPA : How to find sub entities using InheritanceType. 已加入

java - Gradle Jacoco 插件报告零覆盖率

java - 如何让我的代码处理给定的最小值和一个值(如果 < 给定的最小值)

java - 我无法使用 spring 框架将 Hibernate Validator 集成到 javaweb 项目中

java - 使用logstash jcdc输出时出现IllegalAccessError