繁体   English   中英

你如何在 C# 中做*整数* 取幂?

[英]How do you do *integer* exponentiation in C#?

.NET 中的内置Math.Pow()函数将double提升为double指数并返回double结果。

对整数执行相同操作的最佳方法是什么?

补充:似乎可以将Math.Pow()结果转换为 (int),但这会始终产生正确的数字并且没有舍入错误吗?

一个非常快的可能是这样的:

int IntPow(int x, uint pow)
{
    int ret = 1;
    while ( pow != 0 )
    {
        if ( (pow & 1) == 1 )
            ret *= x;
        x *= x;
        pow >>= 1;
    }
    return ret;
}

请注意,这不允许负权力。 我将把它留给你作为练习。 :)

补充:哦,是的,差点忘了 - 还要添加上溢/下溢检查,否则您可能会遇到一些令人讨厌的惊喜。

LINQ有人吗?

public static int Pow(this int bas, int exp)
{
    return Enumerable
          .Repeat(bas, exp)
          .Aggregate(1, (a, b) => a * b);
}

作为扩展使用:

var threeToThePowerOfNine = 3.Pow(9);

使用约翰库克博客链接中的数学,

    public static long IntPower(int x, short power)
    {
        if (power == 0) return 1;
        if (power == 1) return x;
        // ----------------------
        int n = 15;
        while ((power <<= 1) >= 0) n--;

        long tmp = x;
        while (--n > 0)
            tmp = tmp * tmp * 
                 (((power <<= 1) < 0)? x : 1);
        return tmp;
    }           

如果你改变权力的类型,代码将无法工作,为了解决反对意见,好吧......撇开任何改变代码的人他们不理解然后未经测试就使用它的观点......
但是为了解决这个问题,这个版本保护了愚蠢的人免受那个错误......(但不是他们可能会犯的无数其他错误)注意:未经测试。

    public static long IntPower(int x, short power)
    {
        if (power == 0) return 1;
        if (power == 1) return x;
        // ----------------------
        int n = 
            power.GetType() == typeof(short)? 15:
            power.GetType() == typeof(int)? 31:
            power.GetType() == typeof(long)? 63: 0;  

        long tmp = x;
        while (--n > 0)
            tmp = tmp * tmp * 
                 (((power <<= 1) < 0)? x : 1);
        return tmp;
    }

也试试这个递归的等价物(当然更慢):

    public static long IntPower(long x, int power)
    {
        return (power == 0) ? x :
            ((power & 0x1) == 0 ? x : 1) *
                IntPower(x, power >> 1);
    }

怎么样:

public static long IntPow(long a, long b)
{
  long result = 1;
  for (long i = 0; i < b; i++)
    result *= a;
  return result;
}

这是一篇博客文章 ,解释了将整数提升为整数幂的最快方法。 正如其中一条评论指出的那样,其中一些技巧是内置于芯片中的。

非常有趣.. .net 5.0 SimplePower() 现在快 350 倍。 我会说在便携性/性能/可读性方面最好......

    public static int SimplePower(int x, int pow)
    {
        return (int)Math.Pow(x, pow);
    }

这是我过去建造的另一个速度很快的...

    public static int PowerWithSwitch(int x, int pow)
    {
        switch ((uint)pow)
        {
            case 0: return 1;
            case 1: return x;
            case 2: return x * x;
            case 3: return x * x * x;
            case 4: { int t2 = x * x; return t2 * t2; }
            case 5: { int t2 = x * x; return t2 * t2 * x; }
            case 6: { int t3 = x * x * x; return t3 * t3; }
            case 7: { int t3 = x * x * x; return t3 * t3 * x; }
            case 8: { int t3 = x * x * x; return t3 * t3 * x * x; }
            case 9: { int t3 = x * x * x; return t3 * t3 * t3; }
            case 10: { int t3 = x * x * x; return t3 * t3 * t3 * x; }
            case 11: { int t3 = x * x * x; return t3 * t3 * t3 * x * x; }
            case 12: { int t3 = x * x * x; return t3 * t3 * t3 * t3; }
            case 13: { int t3 = x * x * x; return t3 * t3 * t3 * t3 * x; }
            case 14: { int t4 = x * x * x * x; return t4 * t4 * t4 * x * x; }
            case 15: { int t4 = x * x * x * x; return t4 * t4 * t4 * x * x * x; }
            case 16: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4; }
            case 17: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4 * x; }
            case 18: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4 * x * x; }
            case 19: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4 * x * x * x; }
            case 20: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4 * t4; }
            case 21: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4 * t4 * x; }
            case 22: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4 * t4 * x * x; }
            case 23: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4 * t4 * x * x * x; }
            case 24: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4 * t4 * t4; }
            case 25: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4 * t4 * t4 * x; }
            case 26: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4 * t4 * t4 * x * x; }
            case 27: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4 * t4 * t4 * x * x * x; }
            case 28: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4 * t4 * t4 * t4; }
            case 29: { int t4 = x * x * x * x; return t4 * t4 * t4 * t4 * t4 * t4 * t4 * x; }
            default:
                if (x == 0)
                    return 0;
                else if (x == 1)
                    return 1;
                else
                    return (x % 1 == 0) ? int.MaxValue : int.MinValue;
        }
        return 0;
    }

性能测试 (.Net 5)


  • MathPow(Sunsetquest):11 毫秒(.net 4 = 3693 毫秒)<- 快 350 倍!!!

  • PowerWithSwitch(Sunsetquest):145 毫秒(.net 4 = 298 毫秒)

  • 维尔克斯:148 毫秒(.net 4 = 320 毫秒)

  • Evan Moran-递归除法:249 毫秒(.net 4 = 644 毫秒)

  • 迷你我:288 毫秒(.net 4 = 194 毫秒)

  • Charles Bretana(又名库克的):536 毫秒(.net 4 = 950 毫秒)

  • LINQ 版本:4416 毫秒(.net 4 = 3693 毫秒)

(测试说明:AMD Threadripper Gen1,.Net 4 & 5,发布版本,未附加调试器,bases:0-100k,exp:0-10)

注意:在上述测试中几乎没有进行准确性检查。

使用双版本,检查溢出(超过 max int 或 max long)并转换为 int 或 long?

我最喜欢这个问题的解决方案是经典的分而治之的递归解决方案。 它实际上比乘 n 次要快,因为它每次将乘法次数减少一半。

public static int Power(int x, int n)
{
  // Basis
  if (n == 0)
    return 1;
  else if (n == 1)
    return x;

  // Induction
  else if (n % 2 == 1)
    return x * Power(x*x, n/2);
  return Power(x*x, n/2);
}

注意:这不会检查溢出或负 n。

我将结果转换为 int,如下所示:

double exp = 3.0;
int result = (int)Math.Pow(2.0, exp);

在这种情况下,没有舍入错误,因为基数和指数是整数。 结果也将是整数。

对于一个简短的快速单线。

int pow(int i, int exp) => (exp == 0) ? 1 : i * pow(i, exp-1);

没有负指数或溢出检查。

另一种方式是:

int Pow(int value, int pow) {
    var result = value;
    while (pow-- > 1)
        result *= value;
    return pow == 0 ? result : pow == -1 ? 1 : throw new ArgumentOutOfRangeException(nameof(pow));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM