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 < upperLimitbecause we only want numbers smaller than the user's input.
2. 质数标记开关
boolean isPrime = true;
- We start by assuming the current number
numis a prime (set the flag totrue). If we later find a divisor fornum, we'll flip this flag tofalse.
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 tonum-1). - What does
num % divisor == 0mean? The%operator gives the remainder of a division. If this equals 0, it meansdivisordividesnumperfectly—sonumcan't be a prime. - Why use
break? Once we find one valid divisor, we knownumisn'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
isPrimeis stilltrue, that means we found no divisors fornum—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),isPrimestays true → print 2num=3: Same as above → print 3num=4: sqrt(4)=2, divisor=2. 4%2=0 →isPrimebecomes false → no printnum=5: sqrt(5)≈2.23, divisor=2. 5%2=1 → inner loop ends,isPrimestays true → print5- ... and so on, until we finish checking all numbers below 10.
内容的提问来源于stack exchange,提问作者L.Wood22
相关产品推荐
相关产品推荐

