PAT乙级题解1013——数素数(Java)

这篇博客主要解析了PAT乙级试题1013,内容涉及如何使用Java高效地找出指定范围内的素数。博主首先展示了导致运行超时的初始代码,然后给出了通过AC的优化方案,利用预计算素数数组和控制输出格式减少了运行时间。
摘要由CSDN通过智能技术生成

PAT乙级题解1013——数素数(Java)

一:题目
在这里插入图片描述
二:输入输出
输入样例:

5 27

输出样例:

11 13 17 19 23 29 31 37 41 43
47 53 59 61 67 71 73 79 83 89
97 101 103

三:代码

一开始的错误代码,原因是运行超时:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        out(m, n);
    }

    static void out(int m, int n) {
        int i, j, count = 0, num = 1;
        for (i = 2; ; i++) {

            for (j = 2; j < Math.sqrt(i); j++) {
                if (i % j == 0)   //while prime number
                    break;
            }
            if (j > Math.sqrt(i)) {
                count++;
                if (m <= count && count <= n) {
                    if (num % 10 != 0 && count != n) {
                        System.out.print(i + " ");
                        num++;
                    } else {
                        System.out.println(i);
                        num++;
                    }
                }
            }
        }
    }
}

AC代码:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int M = s.nextInt();
        int N = s.nextInt();

        int[] primes = new int[10000];
        int index = 0;
        for (int i = 2; i < 1000000; i++) {
            if (index > 9999)
                break;
            if (isPrime(i))
                primes[index++] = i;
        }

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

            if (count == 9) {
                System.out.println(primes[i]);
                count = 0;
            } else {
                // 如果是最后一个数字,不加空格
                if (i == N-1) {
                    System.out.print(primes[i]);
                } else {
                    System.out.print(primes[i]+" ");
                }
                count++;
            }
        }

    }

    static boolean isPrime(int num) {
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0)
                return false;
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值