我试过这个:
static int myPow(int x)
{
int power = x + 1;
int num = 0;
for (int i = 0; i < power; i++)
{
num = x * i;
x = x + num;
}
return num;
}
如何在不使用 Math.Pow
的情况下通过x+1
分解 int x
?
这个想法是将 X 乘以循环中的 X+1 次。
请按照以下步骤操作:
- 查找电源 (x + 1)
- 变量结果以 x 值开始(结果 = x)
-
循环 i 从 1 到幂,对于每个循环将结果乘以 x,女巫表示 x * x * x * x 次幂时间。
static int myPow(int x) { int power = x + 1; int result = x; for (int i = 1; i < power; i++) { result *= x; } return result; }
看看它在 rextest 上所做的实现
仅供参考,数学中的因式分解是这样的。只是为了好玩,结果可以用平方的幂来计算:
static int myPow(int x, int y)
{
if (y < 0) { throw new ArgumentException("y has to be nonnegative"); }
int result = 1;
while (y > 0)
{
if ((y & 1) == 1)
{
result *= x;
}
x = x * x;
y >>= 1;
}
return result;
}
你可以使用一种叫做平方幂的技术,它非常漂亮,而且速度也更快,它需要 O(lg k) 时间,其中 k 是指数:
static int square(int n){
return n * n;
}
static int pow(int n, int k){
if(k == 1) return n;
if(k % 2 == 1) return n * pow(n, k-1);
return square(pow(n, k/2));
}
然后,如果你想得到 x^(x+1),你只需要 yo 调用pow(x, x+1)
.
小巧、快速、简单,就这么:)