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

Codewars中Execution Timed Out(12000 ms)错误修复咨询

三角形数计算超时优化方案
  • 你当前通过循环累加计算第n个三角形数,时间复杂度为O(n),当n取值极大时会触发超时。
  • 直接使用三角形数的数学公式 n * (n + 1) / 2 计算,时间复杂度降至O(1),可彻底解决超时问题。
  • 优化后的C#代码:
public class Kata
{
    public static int Triangular(int n)
    {
        return n <= 0 ? 0 : n * (n + 1) / 2;
    }
}
  • 代码额外处理了n为非正整数的情况,返回0,和原循环逻辑保持一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:01:16