Java:计算素数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22554373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:27:09  来源:igfitidea点击:

Java:Counting prime numbers

javaprimes

提问by rareinator

So I have written this code, and I am proud of it since I have not been coding for a long time. What it does, it asks for a number and then prints all the Prime numbers there are from 1 to that number.

所以我写了这段代码,我很自豪,因为我已经很长时间没有编码了。它的作用是要求一个数字,然后打印从 1 到该数字的所有质数。

import java.util.Scanner;
class PrimeNumberExample {

    public static void main(String args[]) {

        //get input till which prime number to be printed
        System.out.println("Enter the number till which prime number to be printed: ");
        int limit = new Scanner(System.in).nextInt();

        //printing primer numbers till the limit ( 1 to 100)
        System.out.println("Printing prime number from 1 to " + limit);
        for(int number = 2; number<=limit; number++){
            //print prime numbers only
            if(isPrime(number)){
                System.out.println(number);
            }
        }

    }

    /*
     * Prime number is not divisible by any number other than 1 and itself
     * @return true if number is prime
     */
    public static boolean isPrime(int number){
        for(int i=2; i<number; i++){
            if(number%i == 0){
                return false; //number is divisible so its not prime
            }
        }
        return true; //number is prime now
    }
}

But, what I would like it to do is ask for a number, let us take 10 and then print the first 10 prime numbers, I have tried to see if I could find a way, but I do not know how to since I have not used java that much. I hope that you can and will help me.

但是,我想要它做的是要求一个数字,让我们取 10,然后打印前 10 个素数,我试图看看我是否能找到方法,但我不知道该怎么做,因为我已经有了没怎么用过java。我希望你能并且会帮助我。

采纳答案by laaposto

Just count how many primes number have been printed so far. If this number is more than 10 then stop. Your loop should be like that:

只需计算到目前为止已经打印了多少素数。如果此数字超过 10,则停止。你的循环应该是这样的:

for(int number = 2; number<=limit; number++){
            //print prime numbers only
            if(isPrime(number)){
                System.out.println(number);
                count++; 
            }
        }

Whole code:

全码:

import java.util.Scanner;
class PrimeNumberExample {

    public static void main(String args[]) {

        //get input till which prime number to be printed
        System.out.println("Enter the amount of prime numbers to be printed: ");
        int limit = new Scanner(System.in).nextInt();
        int count=0;

        //printing primer numbers till the limit ( 1 to 100)
        System.out.println("Printing prime number from 1 to " + limit);
        for(int number = 2; number<=limit; number++){
            //print prime numbers only
            if(isPrime(number)){
                System.out.println(number);
                count++; 
            }
        }

    }

    /*
     * Prime number is not divisible by any number other than 1 and itself
     * @return true if number is prime
     */
    public static boolean isPrime(int number){
        for(int i=2; i<number; i++){
            if(number%i == 0){
                return false; //number is divisible so its not prime
            }
        }
        return true; //number is prime now
    }
}

回答by Harmlezz

Try this:

尝试这个:

public static void main(String[] args) throws Exception {

    // get input till which prime number to be printed
    System.out.println("Enter the number till which prime number to be printed: ");
    int limit = new Scanner(System.in).nextInt();

    // printing primer numbers till the limit ( 1 to 100)
    System.out.printf("Printing first %d prime numbers\n", limit);
    for (int number = 2; limit > 0; number++) {
        if (isPrime(number)) {
            System.out.println(number);
            limit--;
        }
    }
}

/*
 * Prime number is not divisible by any number other than 1 and itself
 * 
 * @return true if number is prime
 */
public static boolean isPrime(int number) {
    for (int i = 2; i < number; i++) {
        if (number % i == 0) {
            return false; // number is divisible so its not prime
        }
    }
    return true; // number is prime now
}

回答by Nidhish Krishnan

Try this, its very easy make a count of how many number that are pritning which are prime that all !!!

试试这个,它很容易计算出有多少个数字都是素数!!!

  public static void main(String args[]) {

        //get input till which prime number to be printed
        System.out.println("Enter the number till which prime number to be printed: ");
        int limit = new Scanner(System.in).nextInt();

        //printing primer numbers till the limit ( 1 to 100)
        System.out.println("Printing prime number from 1 to " + limit);
        int count = 0;
        for(int number = 2; count<limit; number++){
            //print prime numbers only
            if(isPrime(number)){
                count++;
                System.out.println(number);
            }
        }

    }

回答by Wundwin Born

Can you try also this way..

你也可以这样试试。。

public static void main(String args[]) {

    //get input till which prime number to be printed
    System.out.println("Enter the number till which prime number to be printed: ");
    int limit = new Scanner(System.in).nextInt();

    //printing primer numbers till the limit ( 1 to 100)
    System.out.println("Printing prime number from 1 to " + limit);
    int number = 2;
    for(int i = 0; i < limit;){         
        //print prime numbers only
        if(isPrime(number)){
            System.out.println(number);
            i++;
        } 
        number = number + 1;
    }

}

/*
 * Prime number is not divisible by any number other than 1 and itself
 * @return true if number is prime
 */
public static boolean isPrime(int number){
    for(int i=2; i<number; i++){
        if(number%i == 0){
            return false; //number is divisible so its not prime
        }
    }
    return true; //number is prime now
}

回答by Airan

Here is one way that can do needful..... I have kept limit as constant 10. you can read it from user too.

这是一种可以做必要的方法......我将限制保持为常数 10。您也可以从用户那里读取它。

public class PrimeNumberExample {

    public static void main(String args[]) {

        //get input till which prime number to be printed
        System.out.println("Enter the number till which prime number to be printed: ");
        int limit = 10;//new Scanner(System.in).nextInt();

        //printing primer numbers till the limit ( 1 to 100)
        System.out.println("Printing prime number from 1 to " + limit);
        int number = 0;
        while(true){
            if(isPrime(++number)){
                System.out.println(number);
                if(--limit <= 0)
                    break;
            }
        }

    }

    /*
     * Prime number is not divisible by any number other than 1 and itself
     * @return true if number is prime
     */
    public static boolean isPrime(int number){
        for(int i=2; i<(number/2); i++){
            if(number%i == 0){
                return false; //number is divisible so its not prime
            }
        }
        return true; //number is prime now
    }
}

回答by user2170172

public boolean isPrime(long pNo) {
    if(pNo > 9) {
        long unitDigit = pNo % 10;
        if(unitDigit == 0 || unitDigit%2 == 0 || unitDigit == 5) {
            return false;
        } else {
            for (long i=3; i < pNo/2; i=i+2) {
                if(pNo%i == 0) {
                    return false;
                }
            }
            return true;
        }
    } else if(pNo < 0) {
        return false;
    }
    else {
        return pNo==2 || pNo==3|| pNo==5 || pNo==7;
    }
}
public int getPrimeNumberCount(long min, long max) {
    int count = 0;
    if(min == max) {
        System.out.println("Invalid range, min and max are equal");
    } else if(max < min || min < 0 || max < 0) {
        System.out.println("Invalid range");
    } else {
        for (long i = min; i <= max; i++) {
            if (isPrime(i) && i > 0) {
                // System.out.println(i);
                count++;
            }
        }
    }
    return count;
}

回答by Ankit Agarwal

Try this, its very easy make a count of how many number that are pritning which are prime that all By using java 8 !!!

试试这个,它很容易通过使用 java 8 计算出有多少个是素数的数字!!!

public static void main(String[] args) {
        Integer maxVal = 100;
        IntStream.iterate(2, i -> ++i)
                .parallel()
                .filter(i -> !IntStream.rangeClosed(2, i/2).anyMatch(j ->  i%j == 0))
                .limit(maxVal)
                .forEach(System.out::println);
    }