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

请求协助实现Pine Script中的最小公倍数(LCM)计算

Fixing LCM Calculation in Pine Script

Hey there! Let's get that LCM calculation working for you. I spotted a few syntax and logic issues in your code that are holding it back—let's break them down and fix things step by step.

What Was Wrong With the Original Code?

  • Reverse loop logic: Your while loop was only running when z was already a common multiple of x and y—that's the opposite of what we need! We need to keep incrementing z until it meets the divisibility condition.
  • Missing variable initialization: The lcm variable wasn't declared before you tried to assign it, which Pine Script doesn't allow.
  • Incorrect loop structure: If the initial z (the larger number) wasn't a multiple, your loop would never run, leaving lcm undefined.

Corrected Code (Loop Approach)

Here's the fixed version of your original loop-based implementation:

//@version=5
indicator(title='LCM Calculator', overlay=false, precision=2, timeframe='')

x = input(15, title="First Number")
y = input(30, title="Second Number")

// Handle edge case: LCM is undefined if either number is 0
if x == 0 or y == 0
    lcm = 0
else
    z = math.max(x, y)
    lcm = z  // Initialize LCM with the larger number first
    // Keep incrementing z until it's divisible by both x and y
    while not (z % x == 0 and z % y == 0)
        z += 1
        lcm = z

plot(lcm, color=color.new(color.black, 0), title="LCM Value")

Even Better: Use GCD for Faster LCM Calculation

For a more efficient approach (especially with large numbers), you can use the mathematical relationship between LCM and GCD:
LCM(a, b) = (a * b) / GCD(a, b)

Pine Script v5 has a built-in math.gcd() function, so we can avoid looping entirely:

//@version=5
indicator(title='LCM Calculator (GCD Method)', overlay=false, precision=2, timeframe='')

x = input(15, title="First Number")
y = input(30, title="Second Number")

if x == 0 or y == 0
    lcm = 0  // LCM is undefined for 0, default to 0
else
    lcm = (x * y) / math.gcd(x, y)

plot(lcm, color=color.new(color.black, 0), title="LCM Value")

This method is way faster because it skips the iterative loop—perfect for any size of input numbers.

内容的提问来源于stack exchange,提问作者Mavi Beyaz Gökyüzü

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 10:44:09