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

求解1-20最小正整数公倍数,Java中find()方法返回错误排查

Troubleshooting Your LCM Finder for 1-20

Hey there! Let's dig into why your find() method is incorrectly returning 2520 when you're looking for the smallest number divisible by all integers from 1 to 20.

First, a quick reality check: 2520 is indeed the least common multiple (LCM) of 1-10, but it fails to divide evenly into several numbers in 11-20. For example:

  • 2520 ÷ 16 = 157.5 (not an integer)
  • 2520 ÷ 17 ≈ 148.23 (nope)
  • 2520 ÷ 19 ≈ 132.63 (definitely not)

So the problem almost certainly lies in how your find() method is verifying divisibility. Here are the most likely culprits and fixes:

Common Issues & Fixes

1. Your divisibility check only covers 1-10, not 1-20

Double-check the loop in your find() method. If you hardcoded the upper limit as 10 instead of 20 (e.g., for(int i=1; i<=10; i++)), that's the immediate problem. Your code thinks it's checking all required numbers, but it's stopping at 10—hence why 2520 passes the check.

2. Your loop exits early incorrectly

If you have logic that returns the number as soon as it passes some checks (instead of all 20), that could also cause this. For example, if you break out of the divisibility loop and return the number before verifying every integer from 1 to 20.

Example of a Working find() Method

Here's a corrected version that properly checks all numbers and optimizes by incrementing by 2520 (since any valid number must be a multiple of 1-10's LCM):

public class Solution {
    public long findSmallestMultiple() {
        long num = 2520; // Start from LCM of 1-10
        while (true) {
            boolean isDivisibleByAll = true;
            // Check every number from 1 to 20
            for (int i = 1; i <= 20; i++) {
                if (num % i != 0) {
                    isDivisibleByAll = false;
                    break; // No need to check further if one fails
                }
            }
            if (isDivisibleByAll) {
                return num; // This will be 232792560, the correct LCM
            }
            num += 2520; // Skip non-multiples of 1-10 to speed things up
        }
    }
}

Bonus: Math-Based Shortcut

Instead of looping, you can calculate the LCM directly using prime factorization. For 1-20, 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—that's your target number.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:32:04