Search code examples
c#performanceoptimizationc#-10.0

Execution Timed Out (12000 ms): How can I optimize this code


My task on codewars was to return true or false depending if the input number is narcissistic number (e.g. 153 = 1^3 + 5^3 + 3^3). But when I tested my code it said that Execution Timed Out (12000 ms) and that I should optimize the code further.

Does anyone know how can i optimize the code below? The code below is written in C#.

public class Kata
{
  public static bool Narcissistic(int value)
  {
    int digit = 0;
    int tempValue=value;
    int checkValue=value;
    int num;
    double sum = 0;

    //number of digits
    while(value!=0){
      value = value%10;
      digit++;
      value=value/10;
    }
    
    //sum
    while(tempValue!=0){
      num=tempValue%10;
      sum=sum+pow(num,digit);
      num=num/10;
    }
    if(sum==checkValue){
      return true;
    }else 
      return false;
  }
  
  //power
  private static int pow(int a,int b){
    int temp = a;
    for(int i=1;i<b;i++){
      a=a*temp;
    }
    return a;
  }
}

Solution

  • In your code tempValue was condition in loop but you never change the value so it's an infinity loop, not about performance

    Maybe you can replace

    while(tempValue!=0) {
        num=tempValue%10;
        sum=sum+pow(num,digit);
        num=num/10;
    }
    

    to

    tempValue = -1;
    while (tempValue != 0)
    {
            int num = tempValue % 10;
            sum += Math.Pow(num, digit);
            tempValue /= 10;
    }
    

    Test case

    Kata.Narcissistic(153);
    // true
    
    // DEBUG / NET6 [If you have care about performance]
    // Time elapsed (ms): 6,998
    // Time elapsed (ns): 7046900