Home > Back-end >  Execution Timed Out (12000 ms) : How can I fix this error
Execution Timed Out (12000 ms) : How can I fix this error

Time:02-05

When i am trying to solve problem on codewars, get this error.

My code passes all the tests but not optimized . Do u have any advice ?

Problem : https://www.codewars.com/kata/525e5a1cb735154b320002c8/train/csharp

C#: code

CodePudding user response:

the problem is that you are using a brute-force solution! when you have an algorithmic/mathematics problem you should think of finding a pattern that can be represented by a formula. in this case, Triangular numbers are already a known problem and there is a solution to it, check out this (https://en.wikipedia.org/wiki/Triangular_number) for more details
so the solution is simple:

public static int Triangular(int n) 
  { 
    // handle the edge case (out-of-range values)
    if (n <= 0)
      return 0;
    
    // apply the triangular numbers formula:
    return (n * (n   1)) / 2;
  } 

CodePudding user response:

This is pure math and does not need any strings. Here is a single line to compute your triangular number which runs in 18ms:

using System;

public class Kata
{
  public static int Triangular(int n)
  {
    return n * (n   1) / 2;
  }
}

This is the definition of a triangular number which maybe explains the code above:

Tn=1 2 3 ⋯ n=n⋅(n 1)2

  • Related