加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 06:02:24 所属栏目:Java 来源:网络整理
导读:我是 Java的初学者.我正在编写这个程序,以显示用户提供的数字之间的所有素数. 目前的输出是: 2,3,5,7,Count: 4 但是,我希望输出如下: “素数的数量是:”count“,它们是:”后面跟逗号分隔的所有数字 package com.example.test;import java.util.Scanner;p
我是 Java的初学者.我正在编写这个程序,以显示用户提供的数字之间的所有素数.

目前的输出是:

2,3,5,7,Count: 4

但是,我希望输出如下:

“素数的数量是:”count“,它们是:”后面跟逗号分隔的所有数字

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

}

解决方法

您必须存储值,例如:
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());
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读