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

Swift求1-20所有数的最小公倍数:嵌套循环问题求助

Fixing Your Nested Loop Issue for Project Euler Problem 5

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 currentNumber and increment it
  • For each number, check if it's divisible by every integer from 1 to 20 using a for loop
  • If it fails any divisibility check (using % to test for remainder), you break out of the for loop 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_divisible variable tracks whether the current number passed all tests. If the for loop breaks early, this flag stays False, so the while loop 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:

  1. Break each number from 1-20 into its prime factors
  2. Take the highest power of each prime present:
    • 2⁴ (from 16), 3² (from 9), 5¹, 7¹, 11¹, 13¹, 17¹, 19¹
  3. Multiply these together: 16 * 9 * 5 * 7 * 11 * 13 * 17 * 19 = 232792560

This gives you the answer instantly, no loops required!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:40:08