Swift求1-20所有数的最小公倍数:嵌套循环问题求助
Hey there! Let's work through this problem you're stuck on—finding the smallest positive number divisible by all integers from 1 to 20. Your approach with a while loop nested inside a for loop makes total sense, but it's easy to trip up on the logic flow here. Let's break down what might be going wrong and fix it.
First, Let's Recap Your Logic (And Where It Might Be Breaking)
You're trying to:
- Start with a
currentNumberand increment it - For each number, check if it's divisible by every integer from 1 to 20 using a
forloop - If it fails any divisibility check (using
%to test for remainder), you break out of theforloop and try the next number
The most common pitfall here is not properly checking if the for loop completed all iterations (i.e., passed every divisibility test). If you break out early, you need a way to tell your while loop to keep going instead of mistaking that break for a success.
A Fixed Version of Your Nested Loop Approach
Here's how to adjust your code (using Python as an example—adapt it to your language of choice):
# Start at 2520 (the smallest number divisible by 1-10) to save time current_number = 2520 found = False while not found: is_divisible = True # Assume it's good until proven otherwise for i in range(1, 21): if current_number % i != 0: is_divisible = False break # No need to check other numbers—this one fails if is_divisible: print(f"The smallest number divisible by 1-20 is: {current_number}") found = True else: # Increment by 2520 instead of 1—since valid numbers must be divisible by 1-10 current_number += 2520
Key Improvements:
- Smart starting point: We begin at 2520 (the answer to the 1-10 problem) because any number divisible by 1-20 must also be divisible by 1-10. This skips thousands of unnecessary checks.
- Explicit success flag: The
is_divisiblevariable tracks whether the current number passed all tests. If theforloop breaks early, this flag staysFalse, so thewhileloop moves to the next number. - Efficient increment: Adding 2520 instead of 1 ensures we only test numbers that are already divisible by 1-10, cutting down the number of iterations drastically.
A Faster Alternative: Calculate the Least Common Multiple (LCM)
Brute-forcing works, but for larger ranges, it's slow. A more efficient way is to calculate the LCM of 1-20 by using prime factorization:
- Break each number from 1-20 into its prime factors
- Take the highest power of each prime present:
- 2⁴ (from 16), 3² (from 9), 5¹, 7¹, 11¹, 13¹, 17¹, 19¹
- Multiply these together:
16 * 9 * 5 * 7 * 11 * 13 * 17 * 19 = 232792560
This gives you the answer instantly, no loops required!
内容的提问来源于stack exchange,提问作者user9603529

