搜索ulong素数c#时的代码优化

Code optimization when searching for ulong prime numbers c#

我正在代码战 (https://www.codewars.com/kata/product-of-consecutive-fib-numbers/train/csharp) 上进行连续 Fib 数乘积挑战,当我弄清楚如何做时,系统提示我的代码耗时太长(超过 12000 毫秒) ) 而且我不知道如何优化它。

提前致谢。

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;
  }

}

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

通过添加 break 可以加快代码速度。但我不确定他们是否通过了所有测试

编辑:

 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;
    }

像那样使用函数