Java 获取范围内的素数和总素数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22508874/
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:09:07  来源:igfitidea点击:

get prime numbers and total prime numbers in range

java

提问by t_godd

I am a beginner in Java. I am writing this program to show all prime numbers in between the number supplied from the user.

我是 Java 的初学者。我正在编写这个程序来显示用户提供的数字之间的所有质数。

Current output is:

当前输出为:

2, 3, 5, 7, Count: 4

But, i want the output to be like:

但是,我希望输出是这样的:

"The number of prime is: "+count+", and they are: " followed by all the numbers separated by comma

"The number of prime is: "+count+", and they are: " followed by all the numbers separated by comma

package com.example.test;

import java.util.Scanner;

public class PrimeTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out
                .println("Enter the number till which the prime numbers are to be calculated: ");
        int input = scanner.nextInt();

        int count = 0;

        // loop through the numbers one by one
        for (int i = 2; i < input; i++) {

            boolean isPrimeNumber = true;

            // check to see if the number is prime
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isPrimeNumber = false;
                    break; // exit the inner for loop
                }
            }

            // print the number if prime
            if (isPrimeNumber) {
                count++;
                System.out.print(i + ", ");

            }

        }
        System.out.println("Count: " + count);
    }

}

采纳答案by libik

You have to store the values, for example like this :

您必须存储这些值,例如像这样:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class PrimeTest {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number till which the prime numbers are to be calculated: ");
        int input = scanner.nextInt();
        List<Integer> primes = new ArrayList<>();

        // loop through the numbers one by one
        for (int i = 2; i < input; i++) {
            boolean isPrimeNumber = true;

            // check to see if the number is prime
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isPrimeNumber = false;
                    break; // exit the inner for loop
                }
            }

            // print the number if prime
            if (isPrimeNumber) {
                primes.add(i);
            }
        }
        System.out.println("The number of prime is: " + primes.size() + ", and they are: " + primes.toString());
    }
}

回答by anirudh

Store the primes in an array and display them at the end, outside the loop.

将素数存储在一个数组中,并在循环外的最后显示它们。

回答by D.R.

Save the generated prime numbers into a List and generate the output in the end. For example:

将生成的素数保存到List中,最后生成输出。例如:

System.out.println("The number of prime is: " + list.size());
foreach(int prime : list)
    System.out.print(prime + ", ");

回答by sp00m

Instead of printing a new found prime (System.out.print(i + ", ");), store it in a list (primes.add(i)), and display this list at the end of your program. Your list must be declared outside your forloop (List<Integer> primes = new ArrayList<Integer>();).

不要打印新找到的素数 ( System.out.print(i + ", ");),而是将其存储在列表 ( primes.add(i)) 中,并在程序结束时显示此列表。您的列表必须在for循环之外声明( List<Integer> primes = new ArrayList<Integer>();)。

回答by t_godd

Thank you every one for helping out.

谢谢大家帮忙。

My final code:

我的最终代码:

package com.example.test;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class PrimeTest {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number till which the prime numbers are to be calculated: ");
        int input = scanner.nextInt();
        scanner.close();
        List<Integer> primes = new ArrayList<>();

        // loop through the numbers one by one (edit include input in range)
        for (int i = 2; i <= input; i++) {
            boolean isPrimeNumber = true;

            // check to see if the number is prime
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isPrimeNumber = false;
                    break; // exit the inner for loop
                }
            }

            // print the number if prime
            if (isPrimeNumber) {
                primes.add(i);
            }
        }
        String s = primes.toString().replace("[", "").replace("]", "");
        System.out.println("The number of prime is: " + primes.size() + ", and they are: " + s);
    }
}

Output:

输出:

Enter the number till which the prime numbers are to be calculated: 70
The number of prime is: 19, and they are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67

回答by Sidarth

Get prime numbers and total prime numbers in range

获取范围内的素数和总素数

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ListPrimeNumbers {

    /**
     * @param args
     * @throws IOException 
     * @throws NumberFormatException 
     */
    public static void main(String[] args) throws NumberFormatException, IOException {

        int count=0;
        int limit;

        System.out.println("Enter the Limit:");

        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);

        limit = Integer.parseInt(in.readLine());

        System.out.println("Prime numbers From 1 to " + limit);

        //loop from 1 to limit
        for(int i=1; i < limit; i++) {

            boolean isPrime = true;

            //check to see if the number is prime
            for(int j=2; j < i ; j++) {

                if(i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            // print the number
            if(isPrime) {
                System.out.print(i + " ");
                count++;
            }
        }
        System.out.println("\nTotal Prime Number in given range: "+count);
    }

}

Output:

输出:

Enter the Limit:

输入限制:

10

10

Prime numbers From 1 to 10

质数从 1 到 10

1 2 3 5 7

1 2 3 5 7

Total Prime Number in given range: 5

给定范围内的总质数:5

回答by Umit Karahan

I wrote one that lists and count the prime numbers between 1 and any given number without using any boolean. May be you find it interesting.

我写了一个列出和计算 1 和任何给定数字之间的素数,而不使用任何布尔值。可能你觉得很有趣。

public class Main {

    public static void main(String[] args) {

        int limit = 30; // The program will show prime numbers between 1 and this limit.
        System.out.println("Prime numbers between 1 and "+limit+" (except the number 2) :");
        System.out.println();
        int amount=1; // The amount will give how many prime numbers exist between the interval.

        for (int dividend =2; dividend <=limit; dividend++) {

            for (int divider=2; divider< dividend; divider++) {
                int remaining = dividend % divider;
                if (remaining==0){
                    break;
                }

                if (divider==dividend-1) {
                    // If the loop manages to come here without having broken, then the dividend a prime number.
                    System.out.println(dividend + " IS A PRIME NUMBER.");

                    amount++;
                }
            }
        }
        System.out.println();
        System.out.println("There are a total of "+amount+" prime numbers between 1 and "+limit+" including the number 2. ");
    }
}

回答by Rahul Sharma

public static void main(String[] args)?

? ? {

? ? ? ? int i,high=10 , low=2,flag ,count=0 ;

? ? ? ??

? ? ? ? while (low<high)

? ? ? ? {

? ? ? ? ? ? flag=0;

? ? ? ? ? ? for (i=2;i<=low/2;i++)

? ? ? ? ? ? {

? ? ? ? ? ? ? ? if (low%i==0)

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? flag=1;

? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? ? ? if (flag==0)

? ? ? ? ? ? { ? ? ??

? ? ? ? ? ? ? ? System.out.println(low);

? ? ? ? ? ? count++;

? ? ? ? }

? ? ? ? ? ? ++low;

? ? ? ? ? ??

? ? ? ? }

? ? ? ??

? ? System.out.println("Total number are: "+count);

}

}

回答by Lakshman Miani

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class PrimeNumbersInRange {
      public static void main(String[] args) {
             int lb = 0, ub = 20;
             List<Integer> list = IntStream.rangeClosed(lb,ub)
                               .filter(PrimeNumbersInRange::isPrime)
                               .boxed()
                               .collect(Collectors.toList());
            System.out.println(list);
            System.out.println(list.size());
      }

      public static boolean isPrime(int num) {
        if (num < 2 || (num > 2 && num % 2 == 0)) {
            return false;
        }

        for (int i = 3; i <= Math.sqrt(num); i++) {
            if (num % i == 0)
                return false;
        }
        return true;
      }
 }