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

Java初学者求助:讲解打印输入上限前所有质数的程序内容

Hey there! I totally get being stuck on that second part when you're just starting out with Java—prime number logic can feel a little tricky at first, but let's break it down step by step.

First, let's assume your teacher's sample code looks something like this (super common for this assignment):

import java.util.Scanner;

public class PrimeFinder {
    public static void main(String[] args) {
        // 第一部分:获取用户输入的上限N
        Scanner input = new Scanner(System.in);
        System.out.print("请输入上限N: ");
        int upperLimit = input.nextInt();
        input.close();

        // ------------------- 你不理解的第二部分 -------------------
        System.out.println("小于" + upperLimit + "的所有质数:");
        for (int num = 2; num < upperLimit; num++) {
            boolean isPrime = true;
            
            for (int divisor = 2; divisor <= Math.sqrt(num); divisor++) {
                if (num % divisor == 0) {
                    isPrime = false;
                    break;
                }
            }
            
            if (isPrime) {
                System.out.print(num + " ");
            }
        }
    }
}
拆解第二部分的核心逻辑

This section's job is to check every number from 2 to N-1, confirm if it's a prime, and print it if it is. Let's split it into digestible chunks:

1. 外层循环:遍历所有待检查的数

for (int num = 2; num < upperLimit; num++) {
  • Primes are defined as numbers greater than 1 that have no divisors other than 1 and themselves, so we start checking from 2 (since 1 isn't a prime).
  • The loop stops at num < upperLimit because we only want numbers smaller than the user's input.

2. 质数标记开关

boolean isPrime = true;
  • We start by assuming the current number num is a prime (set the flag to true). If we later find a divisor for num, we'll flip this flag to false.

3. 内层循环:检查是否存在有效除数

for (int divisor = 2; divisor <= Math.sqrt(num); divisor++) {
    if (num % divisor == 0) {
        isPrime = false;
        break;
    }
}

This is the most confusing part for beginners—let's unpack it:

  • Why stop at Math.sqrt(num)? If a number isn't prime, it can be split into two factors where at least one is ≤ the square root of the number. For example, 15's square root is ~3.87; its factors are 3 and 5, and 3 ≤ 3.87. Checking up to the square root saves us unnecessary work (no need to check all the way to num-1).
  • What does num % divisor == 0 mean? The % operator gives the remainder of a division. If this equals 0, it means divisor divides num perfectly—so num can't be a prime.
  • Why use break? Once we find one valid divisor, we know num isn't a prime. There's no need to check more numbers, so we exit the inner loop immediately to save time.

4. 打印质数

if (isPrime) {
    System.out.print(num + " ");
}
  • After the inner loop finishes, if isPrime is still true, that means we found no divisors for num—so it's a prime! We print it out.

Quick example walkthrough (if N=10)

  • num=2: Inner loop doesn't run (sqrt(2) ≈1.41, so divisor never starts), isPrime stays true → print 2
  • num=3: Same as above → print 3
  • num=4: sqrt(4)=2, divisor=2. 4%2=0 → isPrime becomes false → no print
  • num=5: sqrt(5)≈2.23, divisor=2. 5%2=1 → inner loop ends, isPrime stays true → print5
  • ... and so on, until we finish checking all numbers below 10.

内容的提问来源于stack exchange,提问作者L.Wood22

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:10:13