Search code examples
c#optimizationulong

Code optimization when searching for ulong prime numbers c#


I am doing the Product of consecutive Fib numbers challenge on codewars (https://www.codewars.com/kata/product-of-consecutive-fib-numbers/train/csharp) and when i have figured out how to do it i am prompted with the message that my code takes too long (over 12000 ms) and I do not know how could I optimize it.

Thank you in advance.

public class ProdFib {
  public static ulong[] productFib(ulong prod) {
        ulong F1 = 0;
        ulong F2 = 1;
        ulong t = 0;


        while (F1 * F2 < prod)
          {
            t = F1 + F2;
            F1 = F2;

            F2 = t;
          }
          ulong[] fib = new ulong[3] { F1, F2, 0};
          for ( ulong i = 2; i < prod; i++)
          {
            if (prod % i == 0)
            {
            fib[2] = 1;
            }
          }
        return fib;
  }

}


Solution

  • for ( ulong i = 2; i < prod; i++)
    {
        if (prod % i == 0)
        {
            fib[2] = 1;
            ***break;***
        }
    }
    

    By adding break you can speed your code up. But i'm not sure if they pass all the tests

    edit:

     public static ulong[] productFib(ulong prod)
        {
            ulong F1 = 0;
            ulong F2 = 1;
            ulong t = 0;
    
    
            while (F1 * F2 < prod)
            {
                t = F1 + F2;
                F1 = F2;
    
                F2 = t;
    
            }
            ulong[] fib;
            if (F1*F2 == prod)
            {
                fib = new ulong[3] { F1, F2, 1 };
            }else
            {
                fib = new ulong[3] { F1, F2, 0 };
            }
    
            return fib;
        }
    

    use function like that