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

Java查找指定间隔素数对代码无报错但无法正常运行问题咨询

代码问题排查及修复

存在的核心问题

  • 素数存储逻辑错误:遍历判断素数的for循环内部每次都重新声明int j = 0并执行j++,导致所有找到的素数都被存在arr[1]的位置,之前的素数会被不断覆盖,数组中除了arr[1]存储了最后一个符合要求的素数,其他位置都是初始值0,自然无法匹配到符合间隔要求的素数对。
  • 数组索引使用错误:Java数组下标从0开始,你存储素数时没有正确使用计数变量c作为索引,后续遍历的时候直接把k初始化为c,读取arr[c]拿到的是无效初始值,甚至会触发数组越界异常。

修复后的代码

import java.util.Scanner;
public class EX1_A {

    public static void main(String[] args) 
    {
        Scanner in = new Scanner(System.in);
        System.out.println("please enter the limit of the prime number you want");
        int n = in.nextInt();
        System.out.println("please enter the gap");
        int m = in.nextInt();
        int arr[] = new int[n];
        int c = 0; // 记录找到的素数总数
        // 修复素数存储逻辑
        for(int i = 2; i <= n; i++)
        {
            if(Prime(i))
            {
                arr[c] = i;
                c++;
            }
        }
        
        // 修复遍历索引范围
        for(int k = 0; k < c; k++)
        {
            for(int j = k+1; j < c; j++)
            {
                if(arr[j] - arr[k] == m)
                {
                    System.out.println("the prime numbers with the gap " +m+ " is: {"+arr[k]+","+arr[j]+"}");
                }
                // 可选优化:素数按升序存储,差值超过m后无需继续遍历
                else if(arr[j] - arr[k] > m) {
                    break;
                }
            }
        }
    }
    // 素数判断方法可自行优化循环边界到Math.sqrt(number)提升效率
    public static boolean Prime(int number)
    {
        for(int i = 2; i < number; i++)
        {
            if(number%i == 0)
                return false;
        }
        return true;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:45:04