You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何完善Java质数查找程序?仅在Main类使用System.out

指定范围内查找质数并返回数组的实现方案

需求概述

实现test方法,在整数范围[a, b]内筛选所有质数,存入数组后返回。要求仅允许在Main类中使用System.out输出,已实现质数判断方法isPrime,需补充test方法逻辑,Main类调用代码已完成。


现有代码片段

质数判断方法

private boolean isPrime(int n) {
    for (int i = 2; i < n; i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}

待完善的test方法

public int[] test(int a, int b) {
    //what do I write here
    for (int i = a; i <= b; i++) {
        if (isPrime(i)) {
            //what do I write here, I only want to use syso in the other
            //class(Main).
        }
    }
    return ?;
}

Main类调用代码

public static void main(String... args) {
    Prime p = new Prime();
    System.out.println(p.test(10, 30));
}

完整实现方案

1. 完善test方法及优化isPrime

Java数组长度固定,用ArrayList动态收集质数再转数组是最简洁的方案,同时优化isPrime的边界判断和循环效率:

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

public class Prime {
    private boolean isPrime(int n) {
        // 处理边界:小于2的数不是质数
        if (n <= 1) {
            return false;
        }
        // 循环到平方根即可,减少迭代次数
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    public int[] test(int a, int b) {
        // 用List动态存储质数,无需提前统计数量
        List<Integer> primeList = new ArrayList<>();
        
        for (int i = a; i <= b; i++) {
            if (isPrime(i)) {
                primeList.add(i);
            }
        }
        
        // 将List转换为int数组返回
        int[] primeArray = new int[primeList.size()];
        for (int idx = 0; idx < primeList.size(); idx++) {
            primeArray[idx] = primeList.get(idx);
        }
        
        return primeArray;
    }
}

2. 修正Main类的输出逻辑

直接打印数组会输出对象内存地址,需用Arrays.toString()输出数组内容:

import java.util.Arrays;

public class Main {
    public static void main(String... args) {
        Prime p = new Prime();
        // 用Arrays.toString()打印数组元素
        System.out.println(Arrays.toString(p.test(10, 30)));
    }
}

核心说明

  • 动态收集质数:ArrayList可以灵活添加符合条件的质数,避免提前统计质数数量的冗余步骤
  • 数组转换:通过循环将Integer类型的List转为int[],满足方法返回值要求
  • 质数判断优化:补充小于2的数的判断,同时循环到平方根,大幅减少计算量
  • 正确输出数组:使用Arrays.toString()才能打印出数组的实际元素,而非对象地址

内容的提问来源于stack exchange,提问作者eScape CS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:30:50